Python if Statement
In Python programming,ifthe if statement is the most basic and important conditional control structure. It is used to determine whether to execute a specific block of code based on whether the condition is true or false.
Python'sifif statement is very intuitive and readable. It defines code blocks through indentation, which is a major feature that distinguishes Python from other languages.
Word Definition: ifMeans "if", and is the entry point for conditional judgment.
Basic Syntax and Parameters
ifThe if statement is an independent code block that needs to be used with a conditional expression.
Syntax Format
if 条件表达式:
代码块
Syntax Description
- Conditional expression: Any expression that returns a boolean value (non-zero, non-empty strings, non-empty containers, etc. are considered true).
- Colon: A colon must be added after the conditional expression.
- Indentation: The code block must be indented (usually 4 spaces). The indented code belongs to the if statement's sub-block.
Return Value/Effect
- No return value: The if statement is a control flow statement and does not return any value.
- Effect: When the condition is True, execute the indented code block; otherwise, skip it.
Examples
Let's thoroughly master theifusage of the if statement through a series of examples from simple to complex.
Example 1: Basic Usage - Comparing Number Sizes
Examples
age = 18
if age >= 18:
print("Adult")
print("Program finished")
Expected output:
Adult
Code explanation:
age >= 18is the conditional expression and returns True.- Because the condition is true, execute
print("成年人")。 print("程序结束")is not inside the if indented block, so it will execute regardless of the condition.
Example 2: Checking if a String is Empty
Examples
name = ""
# Empty string is False
if name:
print(f"Hello, {name}")
else:
print("Please enter a name")
# Non-empty string
name = "Tom"
if name:
print(f"Hello, {name}")
Expected output:
请输入名字 你好, Tom
Code explanation:
- In Python, empty strings, empty lists, empty dictionaries, etc., are considered False in conditional checks.
- Non-empty strings are considered True.
Example 3: Multiple Condition Checks
Examples
score = 85
# Using logical operators
if score >= 60 and score < 90:
print("Passed")
# Check multiple conditions (simplified syntax)
if 60 <= score < 90: # Python-specific chained comparison
print("Score is between 60-90")
# Use in to check
colors = ["red", "green", "blue"]
if "red" in colors:
print("Contains red")
Expected output:
及格了 成绩在 60-90 之间 包含红色
Code explanation:
- Python supports chained comparisons, such as
60 <= score < 90。 inThe in operator is used to determine whether an element is in a sequence.
Example 4: Single-line if Expression (Ternary Operator)
Examples
age = 20
# Format: value1 if condition else value2
result = "Adult" if age >= 18 else "Minor"
print(result) # Output: Adult
# More complex example
x = 10
y = 20
max_val = x if x > y else y
print(f"Larger value: {max_val}") # Output: Larger value: 20
Expected output:
成年 较大值: 20
Python's ternary expression is more concise than traditional languages, with the formatvalue1 if condition else value2。
Other Extensions