In programming, we often need programs to make different choices based on various conditions. For example, “If it rains, take an umbrella; if it doesn’t rain, don’t take an umbrella.” This logic of “executing different operations based on conditions” is implemented in Python through the if-else conditional statement.
I. Why Use if-else?¶
Imagine a program without conditional statements—it would only execute code in a fixed order, making it impossible to handle complex scenarios. For instance:
- Determine if a number is positive or negative;
- Check if a score is passing;
- Decide whether to wear a coat based on the weather.
All these scenarios require the program to “first judge the condition, then decide what to do.” The if-else statement is the core tool implementing this logic.
II. Basic Syntax of if-else¶
Python uses indentation to represent code blocks (operations to execute under the same condition). The syntax structure is as follows:
if condition:
# Code to execute when the condition is true (indent with 4 spaces or 1 Tab)
operation1
elif another_condition: # Optional, can have multiple
# Code to execute when the first condition is false but this one is true
operation2
else:
# Code to execute when all conditions are false
operation3
Key Points:
- Colon (:): Required after each condition, indicating the start of an indented code block;
- Indentation: Python uses indentation to distinguish code blocks (typically 4 spaces; avoid mixing with tabs);
- Condition Evaluation: A condition is a “True” or “False” expression, e.g., x > 5 returns True/False.
III. Basic Usage: if Statement¶
Scenario: Judge a single condition. Execute the code if the condition is met; otherwise, skip it.
Example 1: Check if a number is greater than 5¶
# Define a variable
num = 7
# If num > 5, execute the following indented code
if num > 5:
print("This number is greater than 5!") # Indented code block
print("Because 7 is indeed greater than 5~") # Multiple operations in the same block
# This line runs regardless of the condition
print("End of judgment")
Output:
This number is greater than 5!
Because 7 is indeed greater than 5~
End of judgment
Condition Expressions: > (greater than), < (less than), == (equal to, note: two equals, not one!), != (not equal), >= (greater than or equal), <= (less than or equal).
IV. Binary Choice: if-else Statement¶
Scenario: Choose between two conditions: execute A if the first condition is met, else execute B.
Example 2: Check if a score is passing¶
score = 75
if score >= 60: # If score is ≥60
print("Congratulations! You passed!")
else: # If score < 60
print("Unfortunately, you didn't pass~")
Output:
Congratulations! You passed!
If score = 55, the output will be: “Unfortunately, you didn’t pass~”.
V. Multi-Condition Judgment: if-elif-else¶
Scenario: Judge multiple conditions in sequence. The first satisfied condition is executed, and subsequent conditions are skipped.
Example 3: Grade Classification¶
score = 85
if score >= 90: # First check if ≥90
print("Excellent")
elif score >= 80: # Then check if ≥80 (if first fails)
print("Good")
elif score >= 60: # Then check if ≥60 (if first two fail)
print("Passing")
else: # All conditions fail
print("Failing")
Output:
Good
Note: Conditions are evaluated from top to bottom. Once a condition is met, subsequent conditions are not checked. For example, score=95 will match the first condition (≥90) and skip “Good”.
VI. Common Issues and Solutions¶
- Missing Colon: Always add
:after conditions (e.g.,if score > 5:is correct; missing:causes errors); - Indentation Errors: Inconsistent indentation leads to
IndentationError; - Condition Order Mistakes: For example, checking “passing” before “excellent” would make “excellent” unreachable (see Example 3);
- Incorrect Comparison Operators: Using
=(assignment) instead of==(equality check) causes logical errors.
VII. Comprehensive Exercise¶
Problem: Based on an input integer, determine if it is positive, negative, or zero.
# Input an integer
num = int(input("Please enter an integer: "))
if num > 0:
print(f"{num} is positive")
elif num < 0:
print(f"{num} is negative")
else:
print(f"{num} is zero")
Sample Run:
Please enter an integer: -3
-3 is negative
VIII. Summary¶
The if-else conditional statement is one of the most fundamental and commonly used logic control tools in Python. Its core is to enable the program to “make intelligent decisions” through condition evaluation. Remember these key points:
- Use a colon (:) at the end of conditions; indentation defines code blocks;
- Use if-else for binary choices and if-elif-else for multiple conditions;
- Conditions are evaluated top to bottom, with earlier conditions taking precedence;
- Correctly use comparison operators (==, >, <, etc.) and logical operators (and, or, not, to be covered later).
With simple examples and practice, you’ll quickly master if-else usage!