[英]How to use a while loop to print every nth number in a range in Python
I'm working on a practice problem that says, "Use a "while" loop to print out every fifth number counting from 1 to 1000." 我正在处理一个实践问题,它说:“使用“ while”循环来打印出从1到1000的每五个数字。”
I can't seem to make it work. 我似乎无法使其工作。
This is what I've tried so far (as well as several small tweaks of this). 到目前为止,这是我尝试过的(以及对此的一些小调整)。
num = 1
while num in range(1, 1001):
if num % 5 == 0:
num += 1
print(num)
Thank you! 谢谢!
You're close. 你近了 You want to print out every time the condition matches, but increment regardless of the condition.
您希望每次条件匹配时都打印出来,但是无论条件如何都要增加。
num = 1
while num in range(1, 1001):
if num % 5 == 0:
print(num) # print must be inside the condition
num += 1 # the increase must be done on every iteration
for num in range(1, 1001):
if num % 5 == 0:
print(num)
You were pretty close, this should work. 您非常接近,这应该可行。
@Wolf comment is also very helpful for you and relevant! @Wolf评论对您也非常有帮助并且相关!
I would say Python style would be more like: 我会说Python风格更像是:
print(list(range(0, 1001, 5)[1:]))
Got you, yes then for while
loop it looks like: 知道了,是的,然后
while
循环看起来像:
num = 1
while num < 1001:
if not num % 5:
print(num)
num += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.