While, If, Count Statements

bartc bc at freeuk.com
Mon Nov 27 08:26:29 EST 2017


On 27/11/2017 12:54, 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

Because the if-statement is only executed once, then it does the loop.

Try:

count = 0

while count < 10:
   if count < 5:
      print "Hello, I am an if statement and count is", count
   print "Hello, I am a while and count is", count
   count += 1




More information about the Python-list mailing list