Prev: -       |       Next: 'if' control

# 'While' loop¶

## while¶

• The 'while' command performs a repetitive execution of a block of code (block-1 in the example below) as long as a logical condition (boolean expression) is True
In [ ]:
while condition:
block-1
else:
block-2

• The first time that the condition is False the 'else' branch is executed once (block-2 code)

#### Block & Indentation¶

• The following are important Python syntactic rules:

(a) Blocks of code in Python are preceded by a semicolon (':') placed at the end of the enclosing command (see examples below)
(b) Blocks are indented (usuall by 4 spaces) to the right. Please note that identation in Python code is mandatory. Thus, code without proper indentation might not be executed correctly and return runtime errors.

## 'while' examples¶

In [1]:
a = 0
b = 10

while a < b:                 # note the ':'
a += 1                   # note the block indentation of 4 spaces
print(a, end = ' ')
else:                        # note the ':'
print('\nEnd of loop')   # note the block indentation of 4 spaces

print('This is the first code line after the while loop')

1 2 3 4 5 6 7 8 9 10
End of loop
This is the first code line after the while loop

In [2]:
# Draw half christmas tree
lines = 1
maxlines = 10
while lines <= maxlines:
print(lines*'*')
lines +=1

# Change the code to draw the other half tree too

*
**
***
****
*****
******
*******
********
*********
**********

In [4]:
# Play the game!
import random

guess = tries = 0
num = None

while guess != num:
tries += 1
num = int(random.randint(1,5))
guess = int(input('Can you guess the random number? (1 to 5): '))
print('Random number is:',num)
else:
print('Correct guess after',tries,'tries!')

Can you guess the random number? (1 to 5): 2
Random number is: 2
Correct guess after 1 tries!

In [5]:
# Dice game
import random
while input()!='q':
print(random.randint(1,6), random.randint(1,6))

3 4

3 5

6 4
q


. Free learning material
. See full copyright and disclaimer notice