= 18
age if age >= 18:
print("You are an adult")
You are an adult
Conditional if
statements allow programs to make decisions and execute different code based on whether certain conditions are True
or False
. For instance, we may want to perform a different action when a study participant is an adult or not:
IF (participant_age >= 18)
DO SOMETHING
OTHERWISE
DO SOMETHING ELSE
The basic syntax for conditional statements is if condition:
, where condition
is an expression that evaluates to either True
or False
, i.e. a boolean. If it’s True
, the indented code block under the if statement will run. If False
, it will be skipped. For example, the below code will print “You are an adult” if age is 18 or higher.
= 18
age if age >= 18:
print("You are an adult")
You are an adult
You can also add an else
clause to specify code to run if the condition is False
:
= 17
age if age >= 18:
print("You are an adult")
else:
print("You are not an adult")
You are not an adult
For multiple conditions, you can use elif
(else if) clauses to execute the first matching block.
= 14
age if age < 13:
print("You are a child")
elif age < 18:
print("You are a teenager")
else:
print("You are an adult")
You are a teenager
When working out which lines of code will be run, Python will work down the list of if
, elif
s and else
and will run the first one that matches. Once it’s matched one, it will not bother checking to see if any of those later on would have matched. This means that you should order your questions from most-specific to least-specific.
For example, if you want to do one thing for positive numbers, but something special instead for numbers greater than 100, then you should put the more specific check first:
if.py
= int(input("Enter a number: "))
my_number
if my_number > 100:
print(my_number, "is large")
elif my_number > 1:
print(my_number, "is positive")
else:
print(my_number, "negative")
It is possible to ask two or more questions in one go by combining them with and
and or
. So, if you want to check is a number is smaller than ten (my_number < 10
) and is not equal to zero (my_number != 0
), you can use:
if my_number < 10 and my_number != 0:
...
These combined checks can be used in both if
and elif
statements.