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
ifstatement: Used to execute a block of code if a condition is met.elifstatement: Used to execute a block of code if a condition is met after a previous one has not been met.elsestatement: 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
ifstatement is used to check if the variableageis greater than or equal to 18. - If the condition is met, the code block inside the
ifis executed. - If the condition is not met, the code block inside the
elseis 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
ifstatement is used to check if the variableageis greater than or equal to 18. - If the condition is met, it is checked if the variable
ratingis greater than or equal to 6. - If both conditions are met, the first block of code inside the
ifis 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
elseis 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
andoperator is used to combine the conditionsage >= 18andgender == "male". - Only if both conditions are met, the code block inside the
ifis executed.
Exercise Link to heading
Write Python code that determines whether a number is even or odd.