Python Control Flow
If / Else
If a condition is met, do this. Else, do that.
If / Else
if condition:
do this
else:
do thisElif
If the first condition isn’t met, try the next. Stops on the first match.
if condition:
do this
elif condition:
do this instead
elif condition:
do this insteadMultiple ifs
Multiple ifs — if A is met, B and C are still checked.
if condition:
do this
if condition 2:
do this
if condition 3:
do thisNested if/else
if condition:
if another condition:
do this
else:
do this
else:
do thisMembership check (in / not in)
list = ["apple", "banana"]
if "apple" in list:
do this
do that
if "papaya" not in list:
do this
do thatFor loops
A loop that goes through each item.
For loop
word = alphabet
for letter in word:
# the variable letter is now assigned to each character of alphabet
# any imaginable action
print(letter)range()
for x in range(a, b, step):
# any imaginable action
# numbers a to b, not inclusive of b
# default increment is 1. Add step to change.
for x in range(5):
# it goes from 0 to 4Looping >1 lists in a for loop
list_a = [1, 2, 3]
list_b = ["a", "b", "c"]
for x in range(len(list_a)):
print(list_a[x])
print(list_b[x])
# x will cycle from 0 to length-1,
# which is the indexWhile loops
While loop
while condition: # condition is true
do this
while not condition:
do thisEnding the loop
game_not_over = True
while game_not_over:
do this
do that
game_not_over = False
# this ends the while loopFlags
should_continue = True
while should_continue:
Blah
Blah
# should_continue is a Flag
# the flag signals whether the program (loop here) should keep runningUndefined error
while guess != answer:
guess = input("What number do you guess? ")
# guess is not defined prior
# to fix this,
guess = 0 # just define it as 0 LMAO
while guess != answer:
guess = input("What number do you guess? ")Truthiness in loop conditions
True = 1
False = 0
while 20 % 5:
do this
# this loop stops because 20 % 5 is 0
while 21 % 5:
do this
# this loop keeps going because 21 % 5 is more than 0, interpreted as 1 and True.Try / Except
try:
xxx
except:
print("xxx")
# If there's any error in your code under "TRY", then it'll print("xxx")See next
- Python-Functions — defining and calling functions
- Python-Data-Structures — iterating over lists and dicts