Python — Control Flow: If Statements and While Loops

Conditional Tests

A conditional test evaluates to True or False.

Comparison operators

OperatorMeaning
==equal
!=not equal
>greater than
>=greater than or equal
<less than
<=less than or equal

Case-insensitive string comparison

car = 'Audi'
car.lower() == 'audi'    # True

Multiple conditions

age_0 >= 21 and age_1 >= 21   # True only if BOTH are true
age_0 >= 21 or age_1 >= 21    # True if EITHER is true

List membership tests

'trek' in bikes          # True if 'trek' is in the list
'surly' not in bikes     # True if 'surly' is NOT in the list
if players:              # True if non-empty; False if []

Boolean Values

game_active = True
is_valid    = True
can_edit    = False

If Statements

# Simple if
if age >= 18:
    print("You can vote!")
 
# If-else
if age >= 18:
    print("You're old enough to vote!")
else:
    print("You can't vote yet.")
 
# If-elif-else chain
if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age < 65:
    price = 40
else:
    price = 15
print(f"Your cost is ${price}.")

elif vs multiple ifs

Use elif when conditions are mutually exclusive — Python stops checking once a branch matches. Multiple if statements evaluate every condition regardless.

While Loops

A while loop repeats as long as its condition remains true.

current_value = 1
while current_value <= 5:
    print(current_value)
    current_value += 1

break — exit immediately

while True:
    city = input("Enter a city (or 'quit'): ")
    if city == 'quit':
        break
    print(f"I've been to {city}!")

continue — skip rest of this iteration

while True:
    player = input("Add player: ")
    if player == 'quit':
        break
    elif player in banned_users:
        print(f"{player} is banned!")
        continue              # go back to top of loop
    players.append(player)

Flag — boolean variable controls a long-running loop

active = True
while active:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)

Preventing infinite loops

Every while loop needs a guaranteed path to False — via the condition, break, or a flag. If none exists, press Ctrl-C to stop. Flags are preferred when multiple parts of the code might need to end the loop.

Remove all instances of a value

while 'cat' in pets:
    pets.remove('cat')    # remove() only removes first match — loop until none

Cross-References

graph TD
    A[Control Flow] --> B[If statements]
    A --> C[While loops]
    B --> D["Conditional tests: ==, !=, >, <, >=, <="]
    B --> E["Multiple: and / or"]
    B --> F["if / elif / else chain"]
    C --> G["break: exit loop immediately"]
    C --> H["continue: skip to next iteration"]
    C --> I["flag: boolean that controls the loop"]