使用 while 循环检查一系列数字的整除性

Using a while loop to check divisibility of a range of numbers

我正在尝试使用 while 循环检查 1 到 41 范围内的数字 5 和 7 的整除性。我知道还有其他选项,例如 for 循环,但我想了解如何使用 while 循环设置代码。这是我写的代码:

n = 1
m = 41

div = [5,7]

while(n<=m): 
    if n == 13:
        continue
    if n%div[0]==0 and n%div[1]==0:
        print(n, 'the number is divisible for both 5 and 7')    
    elif n%div[0]==0:
        print(n, 'the number is divisible for 5')    
    elif n%div[1]==0:
        print(n, 'the number is divisible for 7')
    else:
        print(n, 'is divisible for neither 5 or 7')

在 Jupyter 会话中,它没有 return 错误,但处理输出需要花费大量时间。谁能告诉我如何正确修改这段代码?

实际上,您的代码永远不会跳出 while 循环。它会一直卡在 while 循环中。您需要在 while 循环中重新更改 n 值:

n = 1
m = 41

div = [5,7]

while(n<=m): 
    if n == 13:
        n += 1
        continue
    if n%div[0]==0 and n%div[1]==0:
        print(n, 'the number is divisible for both 5 and 7')    
    elif n%div[0]==0:
        print(n, 'the number is divisible for 5')    
    elif n%div[1]==0:
        print(n, 'the number is divisible for 7')
    else:
        print(n, 'is divisible for neither 5 or 7')
    n += 1

您需要通过添加来增加 n

n += 1

while 循环的底部。您还需要删除 while 循环主体顶部的 continue 语句。如果没有这两个修复,程序将尝试反复检查一个数字是否可以被 5 或 7 整除而不会终止。


如果您必须跳过特定数字,您应该将 if 语句修改为如下所示:

if n == 13:
    n += 1
    continue

continue 会在 n == 13.

时阻止 while 循环继续前进

除此之外,代码和算法实际上是正确的。你只是忘了设置增量结构 (n+=1).

n = 1
m = 41

div = [5,7]

while(n<=m): 
    if n == 13:
        n+=1
    if n%div[0]==0 and n%div[1]==0:
        print(n, 'the number is divisible for both 5 and 7')    
    elif n%div[0]==0:
        print(n, 'the number is divisible for 5')    
    elif n%div[1]==0:
        print(n, 'the number is divisible for 7')
    else:
        print(n, 'is divisible for neither 5 or 7')
    n+=1

编码愉快 :)

编辑:更正增量语句并添加跳过 13 部分