问题描述
我正在参加 Python 初学者课程,讲师要求我们在不使用递归的情况下倒计时到零.我正在尝试使用 for 循环和范围来这样做,但他说我们必须包括零.
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?
def countDown2(start):
#Add your code here!
for i in range(start, 0, -1):
print(i)
推荐答案
range()
Python 中的函数有 3 个参数:range([start], stop[, step])
.如果你想倒数而不是倒数,你可以将step
设置为负数:
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)
输出:
5
4
3
2
1
0
这篇关于范围倒计时为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!