首页 > 解决方案 > 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?

标签: python

解决方案


这个程序试图找到第一个能被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')

推荐阅读