问题
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)
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/49539187/range-countdown-to-zero