While, If, Count Statements

Frank Millman frank at chagford.com
Tue Nov 28 07:11:19 EST 2017


"Cai Gengyang"  wrote in message 
news:a8335d2c-1fb9-4ba9-b752-418d19e57b01 at googlegroups.com...
>
> On Tuesday, November 28, 2017 at 4:18:04 PM UTC+8, Frank Millman wrote:
> > "Cai Gengyang"  wrote in message
> > news:c2dfc9c4-3e16-480c-aebf-55308177510f at googlegroups.com...
> >
> > > Sure, so how would the code look like if I want the "if" statement to 
> > > be
> > > nested inside the "while" loop
> >
> > Have you tried putting the 'if' statement inside the 'while' loop?
> >
> > If not, give it a shot and see what happens.
> >
> > Frank Millman
>
> I tried this :
>
> 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
>
> but it gives an "indentation error: expected an indented block" with an 
> arrow pointing at the count after the 3rd statement. Indentation error is 
> supposed to be an error about tabs and spaces right ? But I can't find any 
> mistakes with it ...

You are almost there.

An 'if' statement always requires that the following statements are 
indented. This applies even if you are already at one level of indentation.

You could have, for example -

    if a == 'something':
        if b == 'something else':
            if c == 'and another one':
                do_something_if_a_and_b_and_c_are_true()

Or in your case -

    while condition:
        if a == 'something':
            do_something_if_a_is_true()
        continue with while clause

Indentation is fundamental to the way Python works, so if anything above is 
not clear, query it now. It is essential that you have a firm grasp of this.

HTH

Frank





More information about the Python-list mailing list