如何使用while循环在Python中打印范围中的每个第n个数字

问题描述 投票:0回答:3

我正在研究一个练习题,即“使用”而“循环打印出从1到1000的每五个数字。”

我似乎无法使其发挥作用。

这是我到目前为止所尝试的(以及对此的几个小调整)。

num = 1

while num in range(1, 1001):
    if num % 5 == 0:
        num += 1
print(num)

谢谢!

python python-3.x while-loop iteration
3个回答
3
投票

你很亲密您希望每次条件匹配时打印出来,但无论条件如何都要增加。

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

0
投票
for num in range(1, 1001):
    if num % 5 == 0:
        print(num)

你非常接近,这应该工作。

@Wolf评论对你和相关也很有帮助!


0
投票

我会说Python风格更像是:

print(list(range(0, 1001, 5)[1:]))

有你,是的然后为while循环它看起来像:

num = 1
while num < 1001:
    if not num % 5:
        print(num)
    num += 1
© www.soinside.com 2019 - 2024. All rights reserved.