If statements
An if
statement runs a block of code if a specific condition is met, we can use conditional
operators to create these conditions:
- Equal to:
==
- Not equal to:
!=
- Less than:
<
- Greater than:
>
- Greater than or equal to:
>=
- Less than or equal to:
<=
height = 4.1
if height < 4.5:
print("You are not allowed on this ride.")
You have to indent the code, using tab, to make it part of the if statement. Indentation is how python creates blocks of code. Only the block of code in the if statement will run if it’s condition is true.
# All part of the same block
age = 32
name = "John Walker"
rank = "Private"
clearance = False
if rank == "Sergeant":
# A new block inside the if statement
clearance = True
print("Welcome Sergeant")
# Back to the original block
permission = clearance
It’s useful to check for multiple conditions, for that you would use the elif
keyword, which checks
a condition if the condition above it was false.
anniversary = 25
jubilee = ""
if anniversary == 25:
jubilee = "silver"
elif anniversary == 40:
jubilee = "ruby"
elif anniversary == 50:
jubilee = "golden"
elif anniversary == 75:
jubilee = "diamond"
print(f"Congratulations on your {jubilee} jubilee")
Pay attention to the difference between `=` and `==`, `=` is for assigning variables while `==` is for checking equality. Note
If all conditions fail you may run a piece of code using else
, which acts as a kind of default.
rank = "General"
clearance = 0
if rank == "General":
clearance = 4
elif rank == "Colonel":
clearance = 3
elif rank == "Major":
clearance = 2
else:
# If none of the above are true, the else block will run
clearance = 1
if
statements are run sequentially, starting from the top going down, if a condition is met then
the if
statement will exit. So if two conditions are checking for the same thing then only the first
will execute.
weight = 2000
toll_fee = 0
if weight >= 2000:
# Exits here
toll_fee = 500
elif weight >= 2000:
toll_fee = 1500
print(toll_fee) # Output: 500
A condition is just an expression that can evaluate to True
or False
.
Combining conditions
We can combine conditions using and
, which runs a block of code if all it’s conditions are true.
age = 10
height = 5.3
if age > 7 and height > 4.5:
print("You are allowed on this ride")
else:
print("Sorry you may not enter this ride")
Conversely, you can check if either of the conditions are true using or
.
age = 10
height = 5.3
if age > 7 or height > 4.5:
print("You are allowed on this ride")
else:
print("Sorry you may not enter this ride")
A condition can be inverted using not
.
is_raining = True
if not is_raining:
print("Let's go for a walk")