Control Flow

Conditionals

Conditionals are done with the keywords if, elif, and else, and the bodies are indented.

if x > 0:
    print("positive")
if x > 0:
    print("positive")
else:
    print("nonpositive")
if x > 0:
    print("positive")
elif x < 0:
    print("negative")
else:
    print("zero")
Common relations.

Relation

Use

Example

==

Equality

x == 5

!=

Inequality

x != 5

>, >=, <, <=

Inequalities

x > 5

in

Containment

x in [1, 2, 3]

not

Negation

x not in [1, 2, 3]

Loops

For-loops are done with the keyword for, and while-loops with while. Their bodies are indented. The following three code-blocks are equivalent. Each prints the integers 1 through 5.

for i in [1, 2, 3, 4, 5]:
    print(i)
for i in range(1, 6):
    print(i)
i = 1
while i < 6:
    print(i)
    i = i + 1

Loops can be nested. The command break exits the loop. The command continue skips the rest of the current iteration and jumps to the next iteration. An else-block after a loop runs if the loop does not exit from a break.

# Print the primes between 2 and 100
for i in range(2, 101):
    for j in range(2, i):
        if i % j == 0:
            break # Not prime
    else:
        print(f"The number {i} is prime.")

Exceptions

Exceptions are handled with try-except blocks with the keywords try and except with indented bodies.

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")

Exceptions are raised with the keyword raise.

if x < 0:
    raise ValueError("The argument must be nonnegative.")

In some languages, exceptions are avoided by checking beforehand. But, in Python, exceptions are not avoided but handled. That is, Python prefers to ask for forgiveness rather than permission.

import os

# BAD
if os.path.exists("test.txt"):
    with open("data.txt", "r") as f:
        data = f.read()
else:
    data = "No data."

# GOOD
try:
    with open("data.txt", "r") as f:
        data = f.read()
except FileNotFoundError:
    data = "No data."
Common exceptions.

Exception

Use

Exception

Base class for all exceptions and catches everything

AttributeError

When a method or attribute of a class does not exist

ValueError

When an argument of a function is invalid

ZeroDivisionError

Raised when dividing by zero

FileNotFoundError

Raised when a file does not exist

RuntimeError

Fallback for other exceptions at run time