To count up and down in Python, you can use a for
loop in combination with the built-in range()
function. Here’s an example:
Counting up:
# Counting up from 1 to 5
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
In this example, we use the range()
function with two arguments – the start and stop values for the counting sequence. The start
value is inclusive, meaning it will be included in the counting sequence, while the stop
value is exclusive, meaning it will not be included in the counting sequence. The range()
function generates a sequence of numbers from the start value to the stop value – 1.
Counting down:
# Counting down from 5 to 1
for i in range(5, 0, -1):
print(i)
Output:
5
4
3
2
1
In this example, we use the range()
function with three arguments – the start, stop, and step values for the counting sequence. The start
and stop
values work in the same way as in the previous example, defining the range of numbers to be generated. The step
value defines the increment (or decrement) between each consecutive number in the sequence. In this case, we use a step
value of -1 to count down from 5 to 1, decrementing by 1 in each iteration of the loop.
+ There are no comments
Add yours