PyPython · Lesson 3 of 14

Control Flow

Python uses indentation to define code blocks. Not curly braces. Not keywords. Whitespace. If you love arguments, bring this up at your next dinner party.

Python's if/elif/else statements work like you'd expect. The colon after the condition is required, and the body must be indented consistently (4 spaces is the standard). Python uses elif (not else if) for chained conditions.

Python
age = 20

if age < 13:
    print("child")
elif age < 18:
    print("teenager")
elif age < 65:
    print("adult")
else:
    print("senior")

# Comparison operators
x = 10
print(x > 5)    # True
print(x == 10)  # True (== for equality, not =)
print(x != 3)   # True
print(x >= 10)  # True

# Logical operators
print(x > 5 and x < 20)   # True
print(x < 0 or x > 5)     # True
print(not True)             # False

Python has two loop types: for (iterates over a sequence) and while (runs while a condition is true). The for loop is used far more often in idiomatic Python.

Python
# For loop over a range
for i in range(5):
    print(i)   # 0, 1, 2, 3, 4

# range(start, stop, step)
for i in range(0, 10, 2):
    print(i)   # 0, 2, 4, 6, 8

# For loop over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# While loop
count = 0
while count < 5:
    print(count)
    count += 1

# break and continue
for i in range(10):
    if i == 3:
        continue   # skip 3
    if i == 7:
        break      # stop at 7
    print(i)       # 0, 1, 2, 4, 5, 6
◆ Note
Python's "truthy" and "falsy" values: empty strings, empty lists, 0, None, and False are all falsy. Everything else is truthy. This lets you write: if my_list: instead of if len(my_list) > 0: