在python中的while循环中添加多个条件

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

我在 while 循环中添加这 3 个条件时遇到问题,错误在哪里?

n = eval(input("Number: "))

i = 0

while (i % 3 == 0) and (i % 5 == 0) and (i < n):
    print(i, end=" ")
    i = i + 1


     

我希望它打印能被 3 和 5 整除的数字,只要我 < n. If i type in 100 it gives back 0 right now.

python while-loop
1个回答
0
投票

您应该将除法和小于

n
的条件分开,使后者成为
while
循环条件,而前者作为
if
循环内的
while
条件,并且您应该使用
int
代替
eval
获取整数输入值:

n = int(input("Number: "))

i = 0

while i < n:
    if (i % 3 == 0) and (i % 5 == 0):
        print(i, end=" ")
    
    i = i + 1
© www.soinside.com 2019 - 2024. All rights reserved.