单条件判断score = 85if score >= 60:print("考试及格啦!") # 条件成立时执行
二选一判断score = 55if score >= 60:print("考试及格啦!")else:print("考试不及格,要加油!") # 条件不成立时执行
多条件判断(elif可以有多个)score = 92if score >= 90:print("优秀")elif score >= 80:print("良好")elif score >= 60:print("及格")else:print("不及格")
遍历列表fruits = ["苹果", "香蕉", "橙子"]for fruit in fruits:print(f"我喜欢吃{fruit}")# 指定循环次数(range用法)# range(5) 生成 0,1,2,3,4;range(1,6) 生成 1,2,3,4,5for i in range(1, 6):print(f"这是第{i}次循环")
#基本用法count = 1while count <= 3:print(f"当前计数:{count}")count += 1 # 必须修改条件变量,否则会无限循环# 无限循环(需配合break使用)while True:user_input = input("请输入'退出'结束程序:")if user_input == "退出":break # 终止循环print(f"你输入的是:{user_input}")
立即终止当前所在的循环(for/while),跳出循环体 | |
跳过当前循环的剩余代码,直接进入下一次循环 | |
空语句,仅作为占位符,没有任何实际作用(避免语法错误) |
#break示例:找到第一个大于5的数就终止循环numbers = [1, 3, 6, 2, 8]for num in numbers:if num > 5:print(f"找到大于5的数:{num}")break # 终止循环,后续数字不再遍历# continue示例:跳过偶数,只打印奇数for i in range(1, 10):if i % 2 == 0:continue # 跳过偶数,直接进入下一次循环print(f"奇数:{i}")# pass示例:暂时没想好逻辑,先占位if 10 > 5:pass # 不会报错,后续可以补充代码
