Python Program to Print 123…N
Python Program to Print 123…N
In this tutorial, we shall read an integer (N) from the user and print all the numbers from 1 to N to the standard console output.
We shall use looping statements like For Loop and While Loop to iterate from 1 to N.
Example 1: Print 1 to N using For Loop
In this example, we shall use Python For Loop to print all the numbers from 1 to N.
Python Program
n = int(input('Enter N : '))
for i in range(1,n+1):
print(i)Explanation:
- The program first takes input
nfrom the user to define the limit. - The
forloop is used to iterate from 1 ton. - Each number from 1 to
nis printed during each iteration usingprint(i).
Output
Enter N : 4
1
2
3
4Example 2: Print 1 to N using While Loop
In this example, we shall use Python While Loop to print all the numbers from 1 to N.
Python Program
n = int(input('Enter N : '))
i = 1
while i <= n:
print(i)
i += 1Explanation:
- The program takes input
nfrom the user to define the limit. - The
whileloop runs as long as the conditioni <= nis true. - Inside the loop,
print(i)prints the current value ofi, andi += 1increments it until the condition is no longer met.
Output
Enter N : 4
1
2
3
4Example 3: Print Even Numbers from 1 to N
In this example, we will print only the even numbers from 1 to N using a for loop.
Python Program
n = int(input('Enter N : '))
for i in range(2, n+1, 2):
print(i)Explanation:
- The program takes input
nfrom the user to define the limit. - The
range(2, n+1, 2)function starts the iteration at 2 and increments by 2, effectively selecting only even numbers. - Each even number is printed using
print(i).
Output
Enter N : 8
2
4
6
8Example 4: Print Odd Numbers from 1 to N
In this example, we will print only the odd numbers from 1 to N using a while loop.
Python Program
n = int(input('Enter N : '))
i = 1
while i <= n:
print(i)
i += 2Explanation:
- The program takes input
nfrom the user to define the limit. - The
whileloop starts withi = 1, and the increment is set to 2, ensuring that only odd numbers are printed. - Each odd number is printed using
print(i).
Output
Enter N : 7
1
3
5
7Example 5: Print Numbers in Reverse Order from N to 1
In this example, we will print the numbers from N to 1 using a for loop.
Python Program
n = int(input('Enter N : '))
for i in range(n, 0, -1):
print(i)Explanation:
- The program takes input
nfrom the user to define the limit. - The
range(n, 0, -1)function starts atnand decrements by 1 on each iteration. - Each number from N down to 1 is printed using
print(i).
Output
Enter N : 4
4
3
2
1Summary
In this tutorial, we learned how to print all the numbers from 1 to N, for a given N, using different loops like the for loop and while loop. We also covered additional examples that demonstrate printing even and odd numbers, as well as printing numbers in reverse order.