使用 while 循环检查一系列数字的整除性
我正在尝试使用 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 会话上,它没有返回错误,但需要大量时间来处理输出。有人可以告诉我如何正确修改这段代码吗?
I am trying checking the divisibility of 5 and 7 for the numbers in the range from 1 to 41 using a while
loop. I know that there are other options, such as a for
loop, but I would like to understand how the code needs to be set up with a while
loop. This is the code I wrote:
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')
On the Jupyter session, it didn't return an error, but it takes a significant amount of time to process the output. Can someone tell me how to properly modify this code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要通过在
while
循环底部添加:来增加n
。您还需要删除while
循环体顶部的continue
语句。如果没有这两个修复,程序将尝试重复检查一个数字是否可以被 5 或 7 整除,而不会终止。如果必须跳过特定数字,则应将
if
语句修改为如下所示:You need to increment
n
by adding:at the bottom of the
while
loop. You also need to remove thecontinue
statement at the top of the body of thewhile
loop. Without these two fixes, the program will attempt to repeatedly check whether a number is divisible by 5 or 7 without ever terminating.If you must skip a specific number, you should revise the
if
statement to look like the following:当
n == 13
时,continue
会阻止 while 循环继续执行。除此之外,代码和算法实际上是正确的。您只是忘记设置增量结构
(n+=1)
。The
continue
would block the while loop to go any further whenn == 13
.Other than that, the code and algorithm are actually correct. You just forgot to set an incremental structure
(n+=1)
.实际上,您的代码永远不会跳出
while
循环。它总是会卡在 while 循环中。您需要在 while 循环中重新更改n
值:Actually, your code will never get out of the
while
loop. It will always be stuck in the while loop. What you need to rechange then
value in the while loop: