Python 嵌套 if 语句
嵌套 if 语句
你可以在 if 语句内部嵌套 if 语句。这称为 嵌套 if 语句。
实例
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
亲自试一试 »
在这个例子中,只有当外部条件(x > 10)为真时,内部的 if 语句才会执行。
嵌套 if 语句的工作原理
每一层嵌套都会产生更深层次的决策。代码从最外层的条件开始,逐步向内进行评估。
示例
使用嵌套检查多个条件:
age = 25
has_license = True
if age >= 18:
if has_license:
print("You can drive")
else:
print("You need a license")
else:
print("You are too young to drive")
亲自试一试 »
多层嵌套
您可以根据需要嵌套任意层数,但请记住,层数过多会使代码难以阅读。
示例
三层嵌套:
score = 85
attendance = 90
submitted = True
if score >= 60:
if attendance >= 80:
if submitted:
print("Pass with good standing")
else:
print("Pass but missing assignment")
else:
print("Pass but low attendance")
else:
print("Fail")
亲自试一试 »
嵌套 if 语句与逻辑运算符
有时,可以使用逻辑运算符(例如 and)来简化嵌套 if 语句。具体选择取决于您的逻辑。
示例
以下是嵌套 if 语句:
temperature = 25
is_sunny = True
if temperature > 20:
if is_sunny:
print("Perfect beach weather!")
亲自试一试 »
实例
也可以用 and 来编写:
temperature = 25
is_sunny = True
if temperature > 20 and is_sunny:
print("Perfect beach weather!")
亲自试一试 »
两种方法都能产生相同的结果。当内部逻辑复杂或依赖于外部条件时,请使用嵌套的 if 语句。当两个条件都很简单且同等重要时,请使用 and。
更多示例
示例
使用嵌套检查的登录验证:
username = "Emil"
password = "python123"
is_active = True
if username:
if password:
if is_active:
print("Login successful")
else:
print("Account is not active")
else:
print("Password required")
else:
print("Username required")
亲自试一试 »
实例
使用嵌套逻辑进行成绩计算:
score = 92
extra_credit = 5
if score >= 90:
if extra_credit > 0:
print("A+ grade")
else:
print("A grade")
elif score >= 80:
print("B grade")
else:
print("C grade or below")
亲自试一试 »

