Python判断语句

结合-AI智能体学习记录,仅供参考

Python 判断语句是编程中非常基础且重要的部分,用于根据条件执行不同的代码块。在编程三大基本结构中就是分支结构:

1、基本判断语句(if 语句)

 语法结构

if 条件表达式:
    # 条件为 True 时执行的代码块
    print("条件满足")
age = 18
if age >= 18:
    print("你已成年")

2、if-else 语句

语法结构

if 条件表达式:
    # 条件为 True 时执行的代码块
    print("条件满足")
else:
    # 条件为 False 时执行的代码块
    print("条件不满足")
age = 16
if age >= 18:
    print("你已成年")
else:
    print("你未成年")

3、if-elif-else 语句(多条件判断)

语法结构

if 条件1:
    # 条件1为 True 时执行
    print("条件1满足")
elif 条件2:
    # 条件2为 True 时执行
    print("条件2满足")
else:
    # 所有条件都不满足时执行
    print("所有条件都不满足")
score = 85
if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 60:
    print("及格")
else:
    print("不及格")

 4、嵌套判断语句

语法结构

if 条件1:
    # 外层条件为 True 时执行
    if 条件2:
        # 内层条件为 True 时执行
        print("条件1和条件2都满足")
    else:
        # 内层条件为 False 时执行
        print("条件1满足,但条件2不满足")
else:
    print("条件1不满足")
age = 20
is_student = True

if age >= 18:
    if is_student:
        print("你是成年人且是学生")
    else:
        print("你是成年人但不是学生")
else:
    print("你未成年")

5、条件表达式(三元运算符)

语法结构

值1 if 条件 else 值2
age = 16
status = "成年" if age >= 18 else "未成年"
print(status)  # 输出:未成年

 

综合练习:

# 1. 简单判断
x = 10
if x > 5:
    print("x 大于 5")

# 2. if-else
age = 17
if age >= 18:
    print("可以投票")
else:
    print("不能投票")

# 3. if-elif-else
score = 75
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
elif score >= 60:
    print("D")
else:
    print("F")

# 4. 嵌套判断
is_member = True
points = 250

if is_member:
    if points >= 200:
        print("黄金会员")
    elif points >= 100:
        print("白银会员")
    else:
        print("普通会员")
else:
    print("非会员")

# 5. 条件表达式
message = "及格" if score >= 60 else "不及格"
print(message)

# 6. 复杂条件
name = "Alice"
is_student = True
if name == "Alice" and is_student:
    print("找到学生 Alice")

# 7. 检查列表成员
fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
    print("列表中有苹果")

# 8. 检查字符串是否为空
text = ""
if not text:  # 等价于 if len(text) == 0
    print("字符串为空")

你可能感兴趣的:(python基础学习实操,python,开发语言)