Conditionals
In this class, we will delve into conditional statements, which are structures that allow different actions to be executed depending on whether a condition is met or not.
Types of conditional statements: Link to heading
if
statement: Used to execute a block of code if a condition is met.elif
statement: Used to execute a block of code if a condition is met after a previous one has not been met.else
statement: Used to execute a block of code if none of the above conditions are met.
Example Link to heading
age = 18
if age >= 18:
print("You are of legal age.")
else:
print("You are a minor.")
In this example:
- The
if
statement is used to check if the variableage
is greater than or equal to 18. - If the condition is met, the code block inside the
if
is executed. - If the condition is not met, the code block inside the
else
is executed.
Nested statements Link to heading
Conditional statements can be nested within each other.
Example Link to heading
age = 15
rating = 7
if age >= 18:
if rating >= 6:
print("You can get the scholarship.")
else:
print("You can't get the scholarship.")
else:
print("You are not eligible for the scholarship.")
In this example:
- The
if
statement is used to check if the variableage
is greater than or equal to 18. - If the condition is met, it is checked if the variable
rating
is greater than or equal to 6. - If both conditions are met, the first block of code inside the
if
is executed. - If the second condition is not met, the second block of code is executed within the
if
. - If the first condition is not met, the code block inside the
else
is executed.
Logical operators: Link to heading
Logical operators can be used in conditions to combine different conditions.
Example Link to heading
age = 20
gender = "man"
if age >= 18 and gender == "man":
print("You can perform mandatory military service.")
else:
print("You cannot perform mandatory military service.")
In this example:
- The
and
operator is used to combine the conditionsage >= 18
andgender == "male"
. - Only if both conditions are met, the code block inside the
if
is executed.
Exercise Link to heading
Write Python code that determines whether a number is even or odd.