Q:

Python | Program to print numbers from N to 1 (use range() with reverse order)

belongs to collection: Python basic programs

0

Given the value of N and we have to print numbers from N to 1 in Python.

range() Method

This method is used to iterate a range values.

Simply, we use range(start, stop)

Let’s understand by an example, if we want to iterate any loop till a to b, then range statement will be range(a, b+1).

Iterate in reverse order

To iterate range in reverse order, we use 3 parameters

  1. Start – start value
  2. Stop – end value
  3. Step – Increment/Decrement to the value

Examples:

1) To print numbers from B to A

for i in range(B, A-1, -1)
	print i

2) To print numbers from B to A by escaping one number between

for i in range(B, A-1, -2)
	print i

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to print numbers from N to 1 in Python

# Python program to print numbers
# from n to 1

# input the value of n
n = int(input("Enter the value of n: "))

# check the input value
if (n<=1):
	print "n should be greater than 1"
	exit()
	
# print the value of n
print "value of n: ",n

# print the numbers from n to 1
# message
print "numbers from {0} to {1} are: ".format(n,1)

# loop to print numbers 
for i in range(n,0,-1):
	print i

Output 1

    Enter the value of n: 10
    value of n:  10
    numbers from 10 to 1 are: 
    10
    9
    8
    7
    6
    5
    4
    3
    2
    1

Output 2 (when the value of n is 1)

    Enter the value of n: 1
    n should be greater than 1

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Print all numbers between 1 to 1000 which... >>
<< Python | Demonstrate an Example of pass statement...