If / Else / Try / Except

Conditionals in Python


If and Else

x = 20

if (x > 15):
    print("x is greater than 15)
else:
    print("x is less than or equal to 15)

Output:

x is greater than 15

Try and Except

You can also create a function that tries a method and also attempts to catch exceptions.

def floor_div(a, b):
    try:
        # Try to floor divide a and b
        result = a // b
        print("The answer is:", result)
    except ZeroDivisionError:
        print("You cannot divide by zero")

floor_div(4, 2)
floor_div(2, 0)

Output

The answer is:  2
You cannot divide by zero