Conditionals
Conditionals allow a program to make decisions based on certain conditions.
They are one of the most important building blocks in programming because they control the flow of execution.
Basic syntax
In Python, the most common conditional statement is if.
age = 20
if age >= 18:
print("You are an adult")
Let’s break this down:
ifstarts the conditional statementage >= 18is a condition (a boolean expression)- the colon
:marks the start of a code block - the indented line is executed only if the condition is
True
A condition is an expression that evaluates to either True or False.
Boolean expressions
A boolean expression is any expression that results in a boolean value (True or False).
Examples:
x = 10
print(x > 5) # True
print(x == 10) # True
print(x < 3) # False
These expressions are commonly used inside if statements to control the flow of the program.
You can think of them as questions your program asks:
- Is
xgreater than 5? - Is
xequal to 10?
Depending on the answer, the program decides what to do next.
Using else
You can define an alternative path using else. The code block inside the else statement will only run if the initial condition isn't met.
age = 16
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
Using elif
Alternatively, if you need to check multiple conditions, you can use elif:
score = 85
if score >= 90:
print("Excellent")
elif score >= 70:
print("Good")
else:
print("Needs improvement")
Comparison operators
Conditionals often use comparison operators:
==equal to!=not equal to>greater than<less than>=greater than or equal to<=less than or equal to
Logical operators
You can combine conditions using logical operators:
age = 20
has_id = True
if age >= 18 and has_id:
print("Access granted")
and– both conditions must be trueor– at least one condition must be truenot– reverses a condition
Example
temperature = 30
if temperature > 25:
print("It is hot outside")
else:
print("It is not very hot")
Exercise
Now let's practice! Write a program that:
- asks the user for a number
- prints whether the number is positive, negative, or zero
- if the number is positive, it should also print if it's even or odd
To check if a number is even or add, you can evaluate the following expression: n % 2 == 0. If this expression is true, then the number is even! Otherwise, it's odd.
Notes
- Indentation is required in Python and defines code blocks
- Be careful to use
==when comparing values, not= - Keep conditions simple and readable