I am taking a beginner Python class and the instructor has asked us to countdown to zero without using recursion. I am trying to use a for loop and range to do so, but he says we must include the zero.
I searched on the internet and on this website extensively but cannot find the answer to my question. Is there a way I can get range to count down and include the zero at the end when it prints?
Edit:
def countDown2(start):
#Add your code here!
for i in range(start, 0, -1):
print(i)
When called with one parameter, the sequence provided by range always starts with 0. If you ask for range(4) , then you will get 4 values starting with 0. In other words, 0, 1, 2, and finally 3.
Generally, the index range of a list is 0 to n-1 , with n being the total number of values in the list.
As discussed, the increment between two successive numbers is determined using the step parameter in the range() function. We can count down in a for loop in Python using this. For this, the start value should be greater than the end value. The step parameter needs to have a negative value.
The range() method does not include the end number because it generates numbers up to the end number but never includes the end number in its result.
The range()
function in Python has 3 parameters: range([start], stop[, step])
. If you want to count down instead of up, you can set the step
to a negative number:
for i in range(5, -1, -1):
print(i)
Output:
5
4
3
2
1
0
As another option to @chrisz's answer, Python has a built-in reversed()
function which produces an iterator in the reversed order.
start_inclusive = 4
for i in reversed(range(start_inclusive + 1)):
print(i)
outputs
4
3
2
1
0
This can be sometimes easier to read, and for a well-written iterator (e.g. built-in range function), the performance should be the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With