6. Loops¶
6.1 Overview¶
while
for
6.2 While¶
Syntax:
secret = 'swordfish'
pw = ''
while pw != secret:
pw = input("What's the secret word? ")
6.3 For¶
Syntax:
animals = ( 'bear', 'bunny', 'dog', 'cat', 'velociraptor' )
for pet in animals:
print(pet)
6.4 Additional Loop Controls¶
continue
: to shortcut a loop (as if it had reached the end)break
: to break out of the loop prematurelyelse
: only if the loop ends normally (not if a break is used)
Example:
secret = 'swordfish'
pw = ''
auth = False
count = 0
max_attempt = 5
while pw != secret:
count += 1
if count > max_attempt:
print("calling the FBI")
break
if count == 3:
# skip 3rd attempt but continue loop
continue
pw = input(f"{count}: What's the secret word? ")
else:
print('Authorized')