Python Program to Print Numbers 1 to n
You can print numbers from 1 to n in Python using a
for loop like this: for i in range(1, n+1): print(i).Examples
Input1
Output1
Input5
Output1
2
3
4
5
Input0
Output
How to Think About It
To print numbers from 1 to n, start counting from 1 and go up to n, printing each number one by one. Use a loop that repeats this counting and printing until you reach n.
Algorithm
1
Get the input number n.2
Start a counter from 1.3
Repeat until the counter is greater than n:4
Print the current counter value.5
Increase the counter by 1.Code
python
n = int(input("Enter a number: ")) for i in range(1, n + 1): print(i)
Output
Enter a number: 5
1
2
3
4
5
Dry Run
Let's trace the input 3 through the code
1
Input
User enters n = 3
2
Start loop
i starts at 1
3
Print i
Print 1
4
Increment i
i becomes 2
5
Print i
Print 2
6
Increment i
i becomes 3
7
Print i
Print 3
8
Increment i
i becomes 4, loop ends because 4 > 3
| i |
|---|
| 1 |
| 2 |
| 3 |
Why This Works
Step 1: Input number n
We get the number n from the user using input() and convert it to an integer with int().
Step 2: Loop from 1 to n
The for loop with range(1, n+1) runs from 1 up to n, including n.
Step 3: Print each number
Inside the loop, print(i) outputs the current number, showing all numbers from 1 to n.
Alternative Approaches
while loop
python
n = int(input("Enter a number: ")) i = 1 while i <= n: print(i) i += 1
Uses a while loop instead of for; slightly longer but works the same.
using list comprehension and join
python
n = int(input("Enter a number: ")) print('\n'.join(str(i) for i in range(1, n + 1)))
Prints all numbers at once by joining them with newlines; good for compact code.
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs n times, printing each number once, so time grows linearly with n.
Space Complexity
Only a few variables are used, so space stays constant regardless of n.
Which Approach is Fastest?
The for loop and while loop have similar speed; list comprehension with join may be slightly slower due to string operations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loop with range | O(n) | O(1) | Simple and clear printing |
| While loop | O(n) | O(1) | When condition-based looping is preferred |
| List comprehension with join | O(n) | O(n) | Printing all at once, compact code |
Use
range(1, n+1) to include n when looping from 1 to n.Forgetting to add 1 to n in
range() causes the loop to stop before printing n.