range countdown to zero
Question:
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)
Answers:
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.
In the below code n_range doesn’t need to be told to count up or down, it can just tell if the numbers ascend or descend through the power of math. A positive value divided by it’s negative equivalent will output a -1 otherwise it outputs a 1.
def n_range(start, stop):
return range(start, stop, int(abs(stop-start)/(stop-start)))
An input of 5, -1 will output
5
4
3
2
1
0
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)
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.
In the below code n_range doesn’t need to be told to count up or down, it can just tell if the numbers ascend or descend through the power of math. A positive value divided by it’s negative equivalent will output a -1 otherwise it outputs a 1.
def n_range(start, stop):
return range(start, stop, int(abs(stop-start)/(stop-start)))
An input of 5, -1 will output
5
4
3
2
1
0