How to use if in Python

1 min

If clauses are one of the things you will use the most in Python.

There are few variations that you can use.

If and else

The simplest one, contains one condition and if the condition is not met the execution falls to the else statement.

Here is an example.

age = 25

if age >= 18:
	print("Adult")
else:
	print("Not an adult")
Simple if clause

If and else with 2 conditions

It is totally feasible to add multiple conditional statements within the same if clause.

Here is an example.

has_motorbike = True
has_car = True

# If she has either the motorbike permit or car permit she can drive
if has_motorbike or has_car:
	print("Can drive")
else:
	print("Cannot drive")
If clause with two conditions

If, elif and else

Sometimes one conditional statement might not be enough.

To solve that, you can use the if/elif/else.

Where elif is the in between statement between your if and else.

You can use the elif  as much as you want to add other in-between conditions.

age = 25

if age >= 65:
	print("Retired")
elif age >= 18:
	print("Adult")
else:
	print("Not an adult")