Week 4: Guiding Your Code with Conditional Logic
Learn how to make your Python programs make decisions using `if`, `elif`, and `else` statements.
Explore Chapter 4`elif` (else if) Statements: Checking Multiple Conditions.
The `elif` statement allows you to check multiple conditions in sequence. It is used after an `if` statement and before an optional `else` statement. The `elif` condition is checked only if the preceding `if` (or another `elif`) condition was false.
Syntax
if condition1:
# Code to be executed if condition1 is True
elif condition2:
# Code to be executed if condition1 is False AND condition2 is True
elif condition3:
# Code to be executed if condition1 and condition2 are False AND condition3 is True
# ... more elif statements
- You can have multiple `elif` statements after an `if` statement.
- The conditions in the `elif` statements are evaluated in order. As soon as one `elif` condition evaluates to `True`, its corresponding code block is executed, and the rest of the `elif` and `else` blocks are skipped.
Example
grade = 85
if grade >= 90:
print("Excellent!")
elif grade >= 80:
print("Very good.")
elif grade >= 70:
print("Good.")
elif grade >= 60:
print("Pass.")
else:
print("Fail.")
In this example, only one message will be printed based on the value of the `grade` variable.
Nested `if` Statements: Conditions within Conditions.
You can also have `if`, `elif`, and `else` statements inside other `if` statements. This is known as nesting conditional statements. Nesting allows you to create more complex decision-making structures.
Syntax
if outer_condition:
print("Outer condition is True.")
if inner_condition:
print("Inner condition is also True.")
else:
print("Inner condition is False.")
else:
print("Outer condition is False.")
- Be careful with indentation when nesting `if` statements, as it determines which block of code belongs to which condition.
- Excessive nesting can make your code harder to read and understand. In some cases, you might be able to simplify nested conditions using logical operators (`and`, `or`).
Example
age = 25
country = "USA"
if country == "USA":
if age >= 18:
print("You are eligible to vote in the USA.")
else:
print("You are not yet eligible to vote in the USA.")
else:
print("Voting eligibility rules vary by country.")
This example first checks if the `country` is "USA", and then, if it is, it checks the `age` to determine voting eligibility.