Understanding Python if Statements: Syntax, Usage, and Practical Examples
This article explains Python's if statement syntax, including elif and else branches, and provides ten practical code examples that demonstrate basic condition checks, multi‑condition logic, membership tests, error handling, and dynamic condition building for developers of all levels.
In Python programming, conditional statements are essential tools for controlling program flow. By using if statements, developers can execute different code blocks based on varying conditions, enabling logical decision‑making.
Part 1: Introduction The basic if syntax is:
if condition:
# code executed when condition is trueMore complex structures can include elif (else‑if) and else to handle multiple branches:
if condition1:
# code when condition1 is true
elif condition2:
# code when condition2 is true and condition1 is false
else:
# code when all previous conditions are falsePart 2: Usage Scenarios and Examples
Example 1: Basic condition check
age = 18
# Check if age is at least 18
if age >= 18:
print("你已经成年了")
# Usage: verify legal age for certain activitiesExample 2: Multi‑condition grading
score = 75
# Output grade based on score
if score >= 90:
print("优秀")
elif score >= 60:
print("合格")
else:
print("不合格")
# Usage: student grade classificationExample 3: Logical operators
temperature = 32
weather = "rainy"
# Decide whether to go out based on weather and temperature
if temperature < 30 and weather != "rainy":
print("适合外出")
else:
print("不适合外出")
# Usage: make outing decisions based on conditionsExample 4: Membership check
fruits = ["apple", "banana", "cherry"]
fruit = "banana"
# Check if fruit is in the list
if fruit in fruits:
print(f"{fruit} 在水果列表中")
else:
print(f"{fruit} 不在水果列表中")
# Usage: database query or set membership validationExample 5: String comparison
user_input = "yes"
# Confirm user input
if user_input.lower() == "yes":
print("确认成功")
else:
print("取消操作")
# Usage: confirmation dialogs in user interfacesExample 6: Numeric range check
number = 25
# Verify number is within a specific range
if 10 <= number <= 30:
print("数字在指定范围内")
else:
print("数字不在指定范围内")
# Usage: validate data against preset standardsExample 7: File existence check
import os
file_path = "example.txt"
# Check if file exists
if os.path.exists(file_path):
print("文件存在")
else:
print("文件不存在")
# Usage: ensure required files are present in automation scriptsExample 8: Error handling
try:
result = 10 / 0
except ZeroDivisionError:
print("除数不能为零")
else:
if result > 0:
print("结果为正数")
else:
print("结果非正数")
# Usage: safe mathematical calculationsExample 9: Loop with condition
for i in range(5):
if i % 2 == 0:
print(f"{i} 是偶数")
else:
print(f"{i} 是奇数")
# Usage: classify elements in a sequenceExample 10: Dynamic condition construction
condition = True if input("请输入 'yes' 或 'no': ") == "yes" else False
if condition:
print("选择了是")
else:
print("选择了否")
# Usage: adjust program behavior based on user inputThrough these detailed sections, we have learned how to use Python's if statements for condition evaluation and explored a variety of real‑world scenarios. Whether you are a beginner or an experienced developer, continuous practice and experimentation are key to mastering programming concepts.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.