On 11/27/17 7:54 AM, Cai Gengyang wrote: > Input : > > count = 0 > > if count < 5: > print "Hello, I am an if statement and count is", count > > while count < 10: > print "Hello, I am a while and count is", count > count += 1 > > Output : > > Hello, I am an if statement and count is 0 > Hello, I am a while and count is 0 > Hello, I am a while and count is 1 > Hello, I am a while and count is 2 > Hello, I am a while and count is 3 > Hello, I am a while and count is 4 > Hello, I am a while and count is 5 > Hello, I am a while and count is 6 > Hello, I am a while and count is 7 > Hello, I am a while and count is 8 > Hello, I am a while and count is 9 > > The above input gives the output below. Why isn't the output instead : > > Hello, I am an if statement and count is 0 > Hello, I am a while and count is 0 > Hello, I am an if statement and count is 1 > Hello, I am a while and count is 1 > Hello, I am an if statement and count is 2 > Hello, I am a while and count is 2 > Hello, I am an if statement and count is 3 > Hello, I am a while and count is 3 > Hello, I am an if statement and count is 4 > Hello, I am a while and count is 4 > Hello, I am a while and count is 5 > Hello, I am a while and count is 6 > Hello, I am a while and count is 7 > Hello, I am a while and count is 8 > Hello, I am a while and count is 9
It's easy to imagine that this sets up a rule that remains in effect for the rest of the program: â â â if count < 5: â â â â â â â print "Hello, I am an if statement and count is", count But that's not how Python (and most other programming languages) works.â Python reads statements one after another, and executes them as it encounters them.â When it finds the if-statement, it evaluates the condition, and if it is true *at that moment*, it executes the contained statements.â Then it forgets all about that if-statement, and moves on to the next statement. --Ned.
-- https://mail.python.org/mailman/listinfo/python-list