How can you create a for loop that counts down from 5 to 1 in Python?

How can you create a for loop that counts down from 5 to 1 in Python?

a) for i in range(5, 1)
b) for i in range(5, 0, -1)
c) for i in range(1, 5)
d) for i in range(5)

Answer:

b) for i in range(5, 0, -1)

Explanation:

To create a for loop that counts down from 5 to 1 in Python, you can use the range() function with three arguments: start, stop, and step. The step argument is set to -1 to decrement the sequence.

for i in range(5, 0, -1):
    print(i)  # Prints 5, 4, 3, 2, 1

In this example, the loop starts at 5 and decreases by 1 on each iteration until it reaches 1. The stop value of 0 is exclusive, so the loop stops before reaching 0.

This approach is useful when you need to iterate in reverse order, such as when processing data from the end to the beginning or when creating countdown timers.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top