Python Control Flow

If / Else

If a condition is met, do this. Else, do that.

If / Else

if condition:
    do this
else:
    do this

Elif

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 instead

Multiple 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 this

Nested if/else

if condition:
    if another condition:
        do this
    else:
        do this
else:
    do this

Membership check (in / not in)

list = ["apple", "banana"]
 
if "apple" in list:
    do this
    do that
 
if "papaya" not in list:
    do this
    do that

For 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 4

Looping >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 index

While loops

While loop

while condition:        # condition is true
    do this
 
while not condition:
    do this

Ending the loop

game_not_over = True
 
while game_not_over:
    do this
    do that
    game_not_over = False
 
# this ends the while loop

Flags

should_continue = True
while should_continue:
    Blah
    Blah
 
# should_continue is a Flag
# the flag signals whether the program (loop here) should keep running

Undefined 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