Repeat

While Loop

Python

 

While loop

Python 2.7
count = 5

while count > 0:
    count = count - 1
    print(count)

The code inside the while block runs as long as the condition count > 0 evaluates to True.

This will print 4 3 2 1 0 on Console.

 

While Else

Python 2.7
count = 5

while count > 0:
    count = count - 1
    print(count)
else:
    print('done')

The else block in While loop runs when the condition evaluates to False.

The else block won't be run if:

  • break statement executed
  • return statement executed
  • the exception happens inside the block

This will print 4 3 2 1 0 done on Console.

 

Single While loop Statement

Python 2.7
count = 5

while count > 0: print(count); count=count-1

If you only have one statement in your blocks or multiple statements separated by a semicolon (;) in one line, you can have them on the same line as the block header.

This will print 5 4 3 2 1 on Console.