Python 中的 if 语句是一种条件语句,只有在满足特定条件时才会执行代码块。它评估一个返回 True 或 False 的布尔表达式,当条件为 True 时运行缩进的代码块。Python 的 if 语句使程序能够进行决策,允许根据不同的条件执行不同的代码路径。
基本 if 语句语法
Python 中 if 语句的语法很简单:
if condition:
# code to execute if condition is True
statement condition 是一个布尔表达式(如 number > 5 或 name == "Alice"),其计算结果为 True 或 False。如果条件计算结果为 True,则执行缩进的代码块;如果为 False,Python 会完全跳过该块。
示例 1:简单的 if 语句
number = 10
if number > 0:
print("The number is positive") The number is positive
示例 2:条件为 False 的 if 语句
number = -5
if number > 0:
print("The number is positive")
print("This line always executes") This line always executes
在第二个示例中,由于 -5 不大于 0,if 块内的 print 语句被跳过。
if 语句中的缩进
Python 依靠缩进(行首的空白)来定义代码块的作用域,这与使用花括号的其他语言不同。if 块内的所有语句必须缩进相同的量——通常是 4 个空格。
正确的缩进:
age = 20
if age >= 18:
print("You are an adult")
print("You can vote")
print("You have full legal rights") 错误的缩进(会导致错误):
age = 20
if age >= 18:
print("You are an adult") # IndentationError 如果不使用正确的缩进,Python 会引发 IndentationError,因为它无法确定哪些语句属于 if 块。
if 语句中的比较运算符
Python 支持标准的比较运算符,这些运算符返回布尔值,用于 if 语句:
==- 等于!=- 不等于<- 小于<=- 小于或等于>- 大于>=- 大于或等于
示例:使用不同的比较运算符
a = 33
b = 200
if b > a:
print("b is greater than a")
if a != b:
print("a and b are not equal")
if a <= 50:
print("a is 50 or less") b is greater than a a and b are not equal a is 50 or less
if 块中的多个语句
只要所有语句具有相同的缩进级别,就可以在 if 块中包含多个语句。
示例:
score = 95
if score >= 90:
print("Excellent work!")
print("You earned an A grade")
grade = "A"
print(f"Your grade is: {grade}") Excellent work! You earned an A grade Your grade is: A
if 语句中的布尔变量
布尔变量可以直接在 if 语句中使用,无需比较运算符。
示例:
is_logged_in = True
if is_logged_in:
print("Welcome back!")
is_raining = False
if is_raining:
print("Take an umbrella")
else:
print("Enjoy the sunshine") Welcome back! Enjoy the sunshine
Python 在布尔上下文中将某些值视为 False:0、空字符串 ""、None 以及空集合,如 [] 或 {}。所有其他值都被视为 True。
真值和假值
Python 可以在条件语句中将许多类型的值评估为 True 或 False:
假值(评估为 False):
0(零)""(空字符串)None[](空列表)(空字典)()(空元组)
真值(评估为 True):
- 任何非零数字(正数或负数)
- 任何非空字符串
- 非空集合
示例:
name = ""
if name:
print(f"Hello, {name}")
else:
print("Name is empty")
items = [1, 2, 3]
if items:
print("List has items") Name is empty List has items
单行 if 语句
对于简单的条件,可以将 if 语句写在一行上:
标准格式:
temperature = 30
if temperature > 25:
print("It's hot outside") 紧凑格式:
temperature = 30
if temperature > 25: print("It's hot outside") 两个版本产生相同的输出,但单行格式对于简单语句更简洁。
常见用例
用例 1:验证用户输入
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote") 用例 2:检查奇偶数
number = 7
if number % 2 == 0:
print(f"{number} is even") 用例 3:密码验证
password = "secret123"
if len(password) >= 8:
print("Password is strong enough") 用例 4:检查列表内容
shopping_cart = ["apple", "banana", "milk"]
if "milk" in shopping_cart:
print("Milk is in your cart") 要避免的常见错误
错误 1:忘记冒号
# Wrong
if number > 0
print("Positive")
# Correct
if number > 0:
print("Positive") 错误 2:使用 = 而不是 ==
x = 5
# Wrong (assignment, not comparison)
if x = 5:
print("x is 5")
# Correct
if x == 5:
print("x is 5") 错误 3:缩进不一致
# Wrong
if True:
print("Line 1")
print("Line 2") # Different indentation level
# Correct
if True:
print("Line 1")
print("Line 2") 练习示例
示例 1:温度检查器
temperature = 22
if temperature > 30:
print("It's very hot")
if temperature > 20:
print("It's warm")
if temperature < 10:
print("It's cold") It's warm
示例 2:等级分配
marks = 85
if marks >= 90:
print("Grade: A")
if marks >= 80 and marks < 90:
print("Grade: B")
if marks >= 70 and marks < 80:
print("Grade: C") Grade: B
示例 3:成员资格检查
username = "admin"
if username == "admin":
print("Access granted to admin panel")
print("Loading admin dashboard...") Access granted to admin panel Loading admin dashboard...
亲自尝试
通过修改下面的代码来练习您学到的知识。尝试更改值和条件以查看不同的输出!
// 点击"运行代码"查看结果
相关主题
常见问题
Python 中 if 和 if else 有什么区别?
if 语句仅在条件为 True 时执行代码。if else 语句提供了一个在条件为 False 时执行的替代代码块。
在 Python if 语句中,我需要在条件周围使用括号吗?
不需要,括号在 Python 中是可选的。if (x > 5): 和 if x > 5: 都是有效的,但后者更符合 Python 风格。
我可以在单个 if 语句中使用多个条件吗?
可以,您可以使用逻辑运算符(如 and、or 和 not)来组合多个条件:if age >= 18 and has_license:。
如果我在 if 语句后不缩进代码会发生什么?
Python 会引发 IndentationError,因为它需要缩进来定义代码块。