How to Print Number Sequences (1-10 and 10-1) in Python Loops
Generating and printing sequences of numbers, like 1 to 10 or 10 down to 1, is a fundamental programming task.
This guide demonstrates how to achieve this using for loops with range() and reversed(), as well as while loops, providing clear examples for both ascending and descending sequences.
Printing 1 to 10 (Ascending)
Using a for Loop with range() (Recommended)
The range() function combined with a for loop is the most common and Pythonic way to print numbers 1 through 10:
for num in range(1, 11): # Stop value is 11 (exclusive)
print(num)
Output:
1
2
3
4
5
6
7
8
9
10
range(1, 11)generates numbers starting from 1 up to (but not including) 11.- To exclude 10, use
range(1, 10).
Using a while Loop
You can achieve the same result with a while loop, but it's generally more verbose:
number = 1
while number <= 10:
print(number)
number += 1 # Crucial: Increment the counter
Output:
1
2
3
4
5
6
7
8
9
10
- The loop continues as long as
numberis less than or equal to10. - You need to manually increment the
numberin each iteration.
Printing 10 to 1 (Descending)
Using a for Loop with reversed() (Recommended)
The cleanest way to print in reverse order is to use range() to generate the forward sequence and then reverse it with reversed():
for num in reversed(range(1, 11)):
print(num)
Output:
10
9
8
7
6
5
4
3
2
1
range(1, 11)creates the sequence1, 2, ..., 10.reversed(...)returns a reverse iterator for that sequence.
Using a for Loop with range() (Alternative)
You can also use range() directly with a negative step:
for num in range(10, 0, -1): # Start=10, Stop=0 (exclusive), Step=-1
print(num)
Output:
10
9
8
7
6
5
4
3
2
1
- The arguments to the
range()function are start (inclusive), stop (exclusive) and step. - The step of
-1means that the numbers will be generated in reverse order.
Using a while Loop
A while loop can also print numbers in descending order:
number = 10
while number >= 1:
print(number)
number -= 1 # Crucial: Decrement the counter
Output:
10
9
8
7
6
5
4
3
2
1
- The loop continues as long as
numberis greater than or equal to1. - You manually decrement
numberin each iteration.
Conclusion
This guide demonstrated how to print sequences of numbers from 1 to 10 and 10 to 1 in Python.
For both ascending and descending sequences, using a for loop with range() (and reversed() for descending) is generally the most recommended, concise, and Pythonic approach. While while loops offer flexibility, they require manual counter management and are often more verbose for simple sequential tasks.