Prev: - | Next: 'if' control
while condition:
block-1
else:
block-2
(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.
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')
# 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
# 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!')
# Dice game
import random
while input()!='q':
print(random.randint(1,6), random.randint(1,6))
. Free learning material
. See full copyright and disclaimer notice