python - Problem interpreting a "while loop" notation in Python
问题描述
I am reading and solving through the exercises in the book Introduction to Computation and Programming Using Python by John Guttag (used in the MIT courses) and have a problem understanding why a while loop sets x = 1 at the beginning.
The exercise is asking to find a positive integer that is divisible by both 11 and 12. And the sample solution is:
x = 1
while True:
if x%11 == 0 and x%12 == 0:
break
x = x + 1
print(x, 'is divisible by 11 and 12')
#prints 132, which is divisible by both 11 and 12
I´m sorry that this is such a basic question, but I would appreciate if someone could explain to me the logic of setting x = 1 at the beginning, if x is the value that we are solving for in the first place. Also, I don´t understand the x = x+1 part.
Also, what is the notation I should use to tell a program to do something based on the condition "of all existing integers/values"... (followed by a for or while loop)? Is that what x = 1 possibly refers to?
解决方案
这个程序试图找到第一个能被11
和整除的严格正整数12
。
为此,您需要从某个地方开始,这是一个正数x = 1
。如果我们将其设置为 0,那么这将是我们的结果,但我们需要一个严格的正数。
所以我们试着看看新x
的是否可以整除,如果不是,我们将它加一。
一个更好的程序是:
x = 1
while x%11 != 0 or x%12 != 0:
x = x + 1
print(x, 'is divisible by 11 and 12')
推荐阅读
- onbase - 如何在 OnBase13 的重复部分上应用 SUM() 函数
- python - 是否可以使用 Python 复制“正在使用”的文件?(网络驱动器中的文件)
- database - 在 SQLite 中连接来自不同表的两个字段
- bash - SSH 命令执行/变量替换问题
- javascript - 如何将 jQuery 文件加载到我的 Flask 项目中以使 CSP 无效
- karate - 空手道认证仅对场景中的第一个请求有效
- ruby-on-rails - 难以将正则表达式应用于 Rails 视图。我应该让它成为一个辅助方法吗?
- for-loop - 在 Google 应用程序脚本中循环动态范围以替换某些值
- unity3d - 异常:il2cpp.exe 没有正常运行
- ios - 视频未在 youtube 快速助手上加载