Loops
Appearance
while Loops
my_number = 1
while my_number <= 10: # set loop condition
print(my_number) # do something
my_number += 1 # increase condition variable
Keep running until the user quits
prompt = "Enter a message to share.\nEnter 'quit' to quit: "
entry = ""
while entry != 'quit': # set loop condition
entry = input(prompt)
if entry != 'quit': # check loop condition
print(entry)
else:
print("You quit the program.")
Use a Flag
prompt = "Enter a message to share.\nEnter 'quit' to quit: "
state = True # set flag to true
entry = ""
while state: # loop condition based on flag
entry = input(prompt)
if entry == 'quit':
state = False
print("You quit the program.")
else:
print(entry)
Use while True and break
prompt = "Enter a message to share.\nEnter 'quit' to quit: "
entry = ""
while True: # will continue until break
entry = input(prompt)
if entry == 'quit':
break
else:
print(entry)
print("You quit the program.")
Use continue
my_number = 0
while my_number < 10:
my_number += 1
if my_number % 2 ==0:
continue # go back to start of loop (without doing next line)
print(my_number)