IF 语句的使用方法
沸点数:18
作者:madama
生成时间:2025-04-17 19:18:29
来源:https://doc.ciilii.com/
参考资料
IF 语句的使用方法
IF 语句使用方法
功能
IF 语句用于根据条件判断执行不同的代码块,当条件为真时执行一段代码,否则执行另一段代码。
语法
if condition: # 条件为真时执行的代码 else: # 条件为假时执行的代码
参数说明
condition:布尔表达式,结果为True或False。else:可选部分,当condition为False时执行。
用法
单独使用
if:if condition: # 条件为真时执行
使用
if-else:if condition: # 条件为真时执行 else: # 条件为假时执行
使用
if-elif-else(多条件判断):if condition1: # 条件1为真时执行 elif condition2: # 条件2为真时执行 else: # 其他情况执行
示例
基本示例:
x = 10 if x > 5: print("x 大于 5") else: print("x 不大于 5")多条件判断:
score = 85 if score >= 90: print("优秀") elif score >= 80: print("良好") elif score >= 60: print("及格") else: print("不及格")
注意事项
缩进必须一致,通常使用 4 个空格。
condition必须返回布尔值(True或False)。elif可以有多个,但else只能有一个且必须在最后。嵌套
if语句时,注意缩进层级。
作者:王壹杰
时间:2025-04-17 19:18:29
来源:https://doc.ciilii.com/
时间:2025-04-17 19:18:29
来源:https://doc.ciilii.com/
