While, If, Count Statements

Ned Batchelder ned at nedbatchelder.com
Mon Nov 27 10:59:35 EST 2017


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.



More information about the Python-list mailing list