Basic questions for python beginners about while loop
大家讲道理
大家讲道理 2017-05-24 11:35:01
0
2
537

Title: Use python to print all even numbers within 100

The first code

n = 1
i = 2*n
while i <= 100:
    print(i)
    n+=1

Code execution result: infinite printing number 2

Second code:

n = 1
i = 2*n
while i <= 100:
    print(i)
    n+=1
    i = 2*n

Code execution result: correct printing

My question:
Why is the result printed by the first piece of code wrong? The second piece of code just adds i=2*n to the while loop and the result is correct? Is it possible that in the first piece of code, where n = 1, n cannot change the value of i while n is constantly adding 1? Why?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
伊谢尔伦

In the loop, there is no change in the execution of i = 2*n,它的值又怎么会改变. 只有执行了相应的语句,才会改变的.
初始赋值 i = 2*n, i的值不会动态的随n. It will change only when the corresponding statement is executed.

仅有的幸福

Yes, adding 1 to n in the first piece of code does not change the value of i, i is always 2.

while循环的语法是:
while 条件:
    code...

As long as the condition meets True, it will keep looping.

The condition of the first paragraph has always been i < 100, that is, 2 < 100, which satisfies the condition, so it will continue to loop.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template