Home »
Python »
Python programs
Python | Program to print numbers from N to 1 (use range() with reverse order)
Here, we will learn how to print numbers in reverse order i.e. how to use range() method in reverse order/ decreasing steps.
Submitted by IncludeHelp, on July 29, 2018
Problem statement
Given the value of N and we have to print numbers from N to 1 in Python.
Iterate a range values
To iterate a range values, the range() method is used. Simply, you can 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 a range values in reverse order
To iterate range in reverse order, we use 3 parameters
- Start – start value
- Stop – end value
- 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
Python program to print numbers from N to 1
# 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
Python Basic Programs »