range countdown to zero

心不动则不痛 提交于 2020-05-29 04:50:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!