This chapter details the fundamental concept of Control Flow, specifically how to use conditional statements (if, elif, else) to make decisions in your code based on Boolean logic and comparisons.
Control Flow refers to the order in which individual statements or instructions are executed in a program. Conditional statements allow you to execute different code blocks depending on whether a specific condition is True or False.
1. Comparison Operators
Conditional statements rely on comparison operators to evaluate relationships between values, always returning a Boolean result (True or False).
| Operator | Meaning | Example | Result |
== | Equal to | x == 10 | True if $x$ is 10 |
!= | Not equal to | x != 10 | True if $x$ is not 10 |
> | Greater than | x > 10 | True if $x$ is larger than 10 |
< | Less than | x < 10 | True if $x$ is smaller than 10 |
>= | Greater than or equal to | x >= 10 | True if $x$ is 10 or greater |
<= | Less than or equal to | x <= 10 | True if $x$ is 10 or smaller |
2. Boolean Logic Operators
These operators combine multiple conditional expressions.
| Operator | Meaning | Example |
and | Returns True if both conditions are True. | age > 18 and is_citizen |
or | Returns True if at least one condition is True. | day == "Sat" or day == "Sun" |
not | Reverses the Boolean result (turns True into False and vice versa). | not is_logged_in |
3. The if Statement (Basic Condition)
The if statement is the simplest form of conditional control flow. If the condition following if is True, the indented block of code is executed.
score = 85
if score > 80:
print("Excellent work!") # Executes if score is > 80
4. The if...else Statement (Two-Way Decision)
The else statement provides an alternative code block to execute if the initial if condition is False.
is_raining = False
if is_raining:
print("Take an umbrella.")
else:
print("Enjoy the sunny weather.") # Executes because is_raining is False
5. The if...elif...else Statement (Multi-Way Decision)
When you need to check several mutually exclusive conditions, you use elif (short for “else if”). Python checks conditions in order, and only the code block for the first True condition is executed.
grade = 72
if grade >= 90:
print("A")
elif grade >= 80: # Checked only if grade < 90
print("B")
elif grade >= 70: # Checked only if grade < 80
print("C") # Executes because 72 >= 70
else:
print("F")
6. The Ternary Operator (Conditional Expression)
Python offers a concise way to assign a value to a variable based on a single condition, often called the ternary operator or conditional expression.
Syntax: value_if_true if condition else value_if_false
user_status = 19
message = "Adult" if user_status >= 18 else "Minor"
print(message) # Output: Adult
