If Statements (Python)

This tutorial module covers conditional if…else statements in Python.

In Python, we use if to determine whether a certain condition has been satisfied.

The if statement establishing the condition is aligned to the left, and the operation dependent on the condition is indented:

a = 10
b = 20

if a < b:
 print("a is smaller than b")
> a is smaller than b

We can use the keyword “elif” (short for “else if”) to add further conditions to be considered in sequence:

a = 20
b = 10

if a < b:
 print("a is smaller than b")
elif a > b:
 print("b is smaller than a")
> b is smaller than a

We can use the keyword “else” to include any other possibilities not explicitly matched by the previous conditions:

a = 10
b = 10

if a < b:
 print("a is smaller than b")
elif a > b:
 print("b is smaller than a")
else:
 print("a is equal to b")
> a is equal to be

You can establish compound conditions using logical operators like “and”:

a = 1
b = 2

if (a > 0) and (b > a):
 print("b is greater than zero")

We can also use “or”:

a = 1

if (a < 0) or (a > 0):
 print("a is not equal to zero")
> a is not equal to zero

For more, check out the w3schools page on if…else statements.