Files
2026-05-06 11:21:42 +08:00

69 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# if 语句有三种基本形式:if if-else 和 if-elif-else。
age = 20
if age >= 18:
print("成年了")
# if 条件: else:
age = 16
if age >= 18:
print("成年了")
else:
print("未成年")
# 形式三:if-elif-else 语句
# 用于判断多种可能的情况。程序会按顺序检查每一个 elif 的条件,一旦某个条件为 True,就执行对应的代码块,然后跳出整个 if 结构。如果所有 if 和 elif 的条件都不满足,则执行 else 的代码块。
score = 90
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
else:
print("不及格")
# 关键细节
# 使用缩进来区分代码块
# 通常使用4个空格作为一个缩进级别
# 同一个代码块的语句必须相同的缩进
# 条件表达式
# if 后面的“条件”可以是很广泛的表达式,其结果会被判断为 True 或 False。
# 比较运算符: == (等于), != (不等于), > (大于), < (小于), >= (大于等于), <= (小于等于)
# 逻辑运算符: and (与), or (或), not (非)
# 成员运算符: in (在...内), not in (不在...内)
age = 25
is_student = True
# 使用 and
if age >= 18 and is_student:
print("您是成年学生。")
# 使用 or
if age < 12 or age >= 65:
print("您可以享受优惠票价。")
# 使用 not
if not is_student:
print("您不是学生。")
# 使用 in
name = "Alice"
if name in ["Alice", "Bob", "Charlie"]:
print(f"你好,{name}")
# 嵌套的 if 语句
num = 10
if num > 0:
print("数字是正数")
if num % 2 == 0:
print("偶数")
else:
print("奇数")
else:
print("数字是0或者负数")
result = "11" * 2
print(result)