Python If...Else

Python If ... Else

Python supports the usual logical conditions from mathematics. These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Basic If Statement

a = 33
b = 200
if b > a:
  print("b is greater than a")

Indentation: Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.


Elif and Else

The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".

The else keyword catches anything which isn't caught by the preceding conditions.

Elif and Else Example

a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

Short Hand If ... Else (Ternary Operator)

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

a = 2
b = 330
print("A") if a > b else print("B")

Exercise

?

Which keyword do you use to check an alternative condition if the first if fails?