5.1 Decision statements
5.1a What are Python decision statements
Decision statements in Python allow a program to execute certain pieces of code based on specific conditions. The primary decision statements are if
, elif
, and else
.
-
if statement: This statement checks a condition. If the condition is true, the code block inside the if statement is executed.
-
elif statement: This stands for "else if" and provides additional conditions to check if the initial if condition is false. You can have multiple elif statements to check multiple conditions.
-
else statement: This statement is executed if none of the previous conditions (
if
orelif
) are true.
5.1b Why do we use decision statements?
Decision statements are essential for controlling the flow of a program. They allow programs to make decisions and execute specific code blocks based on different conditions, enabling more complex and dynamic behavior.-
Here’s a simple example to demonstrate how if
, elif
, and else
statements work in Python:
Example 5.1.1 - Example of decision statements
age = 14
if age < 13:
print("You are a child.")
elif age >= 13 and age < 20:
print("You are a teenager.")
else:
print("You are an adult.")
You are a teenager.
Example 5.1.1 - Explanation
-
if age < 13:
- This checks if the value of age is less than 13. If true, it prints "You are a child.". -
elif age >= 13
andage < 20
- If the if condition is false, this checks if the value of age is between 13 and 19 (inclusive). If true, it prints "You are a teenager.". -
else
- If neither theif
nor theelif
conditions are true, this block is executed, printing"You are an adult."
.
Note
As you can see decision statements like if
, elif
, and else
are crucial for writing programs that can react to different inputs and conditions, making them flexible and interactive.