第5篇:条件语句与循环语句

目录

程序控制结构概述

程序控制结构决定了程序中语句的执行顺序。Python中有三种基本控制结构:

  1. 顺序结构:程序按照代码书写的顺序依次执行
  2. 选择结构:根据条件判断选择执行不同的代码分支
  3. 循环结构:重复执行某段代码直到满足特定条件

条件语句

条件语句允许程序根据不同条件执行不同的代码路径。

布尔表达式

条件语句的核心是布尔表达式,其结果为True或False。

# 简单的布尔表达式
age = 20
print(age >= 18)  # 输出:True

# 复合布尔表达式
score = 85
print(score >= 60 and score < 90)  # 输出:True

# 使用变量作为条件
is_raining = True
if is_raining:
    print("记得带伞")

if语句

最基本的条件语句,只在条件为True时执行代码块。

语法结构

if 条件:
    # 条件为True时执行的代码
    语句1
    语句2
    ...

基本示例

# 简单的if语句
age = 20
if age >= 18:
    print("您已成年")
    print("可以投票")

print("程序继续执行")

# 数值比较
temperature = 30
if temperature > 25:
    print("天气很热,注意防暑")

# 字符串比较
username = "admin"
if username == "admin":
    print("欢迎管理员")

if-else语句

提供两种互斥的选择,条件为True时执行if分支,否则执行else分支。

语法结构

if 条件:
    # 条件为True时执行的代码
    语句1
    语句2
    ...
else:
    # 条件为False时执行的代码
    语句1
    语句2
    ...

基本示例

# 判断奇偶数
number = 7
if number % 2 == 0:
    print(f"{number} 是偶数")
else:
    print(f"{number} 是奇数")

# 用户登录验证
input_username = "user123"
correct_username = "admin"
if input_username == correct_username:
    print("登录成功")
else:
    print("用户名错误")

# 成绩判定
score = 75
if score >= 60:
    print("考试通过")
else:
    print("考试未通过")

if-elif-else语句

用于处理多个条件分支,按顺序检查每个条件。

语法结构

if 条件1:
    # 条件1为True时执行的代码
    语句1
    ...
elif 条件2:
    # 条件2为True时执行的代码
    语句1
    ...
elif 条件3:
    # 条件3为True时执行的代码
    语句1
    ...
else:
    # 所有条件都为False时执行的代码
    语句1
    ...

基本示例

# 成绩等级判定
score = 85

if score >= 90:
    grade = "优秀"
elif score >= 80:
    grade = "良好"
elif score >= 70:
    grade = "中等"
elif score >= 60:
    grade = "及格"
else:
    grade = "不及格"

print(f"分数:{score},等级:{grade}")

# 星期几判断
day = 3

if day == 1:
    weekday = "星期一"
elif day == 2:
    weekday = "星期二"
elif day == 3:
    weekday = "星期三"
elif day == 4:
    weekday = "星期四"
elif day == 5:
    weekday = "星期五"
elif day == 6:
    weekday = "星期六"
elif day == 7:
    weekday = "星期日"
else:
    weekday = "无效日期"

print(f"今天是{weekday}")

嵌套条件语句

在一个条件语句内部包含另一个条件语句。

基本示例

# 用户登录系统
username = "admin"
password = "123456"
role = "admin"

if username == "admin":
    if password == "123456":
        if role == "admin":
            print("管理员登录成功")
        else:
            print("普通用户登录成功")
    else:
        print("密码错误")
else:
    print("用户名不存在")

# 年龄和身高的综合判断
age = 25
height = 175

if age >= 18:
    if height >= 170:
        print("符合成年人标准且身高达标")
    else:
        print("符合成年人标准但身高不足")
else:
    if height >= 150:
        print("未成年但身高达标")
    else:
        print("未成年且身高不足")

三元运算符

三元运算符是if-else语句的简写形式。

语法结构

变量 =1 if 条件 else2

基本示例

# 简单的三元运算符
age = 20
status = "成年" if age >= 18 else "未成年"
print(status)  # 输出:成年

# 数值比较
a, b = 10, 20
max_value = a if a > b else b
print(max_value)  # 输出:20

# 字符串处理
name = ""
greeting = f"您好,{name}" if name else "您好,访客"
print(greeting)  # 输出:您好,访客

# 列表操作
numbers = [1, 2, 3]
result = numbers if len(numbers) > 0 else [0]
print(result)  # 输出:[1, 2, 3]

while循环

while循环在条件为True时重复执行代码块。

语法结构

while 条件:
    # 条件为True时执行的代码
    语句1
    语句2
    ...

基本示例

# 简单的计数循环
count = 1
while count <= 5:
    print(f"第{count}次循环")
    count += 1

print("循环结束")

# 用户输入验证
password = ""
while password != "123456":
    password = input("请输入密码:")
    if password != "123456":
        print("密码错误,请重新输入")

print("密码正确,登录成功")

# 计算1到100的和
total = 0
i = 1
while i <= 100:
    total += i
    i += 1

print(f"1到100的和为:{total}")

无限循环与break语句

# 无限循环示例
while True:
    user_input = input("输入'quit'退出程序:")
    if user_input == "quit":
        print("程序退出")
        break
    else:
        print(f"您输入的是:{user_input}")

for循环

for循环用于遍历序列(如列表、字符串、元组等)或其他可迭代对象。

语法结构

for 变量 in 可迭代对象:
    # 遍历每个元素时执行的代码
    语句1
    语句2
    ...

基本示例

# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
    print(f"我喜欢吃{fruit}")

# 遍历字符串
word = "Python"
for char in word:
    print(char)

# 遍历元组
coordinates = (10, 20, 30)
for coord in coordinates:
    print(coord)

# 遍历字典的键
person = {"name": "张三", "age": 25, "city": "北京"}
for key in person:
    print(f"{key}: {person[key]}")

range()函数

range()函数常用于生成数字序列。

# 基本用法
for i in range(5):  # 生成0到4的数字
    print(i)
# 输出:0 1 2 3 4

# 指定起始值和结束值
for i in range(2, 8):  # 生成2到7的数字
    print(i)
# 输出:2 3 4 5 6 7

# 指定步长
for i in range(0, 10, 2):  # 生成0到9的偶数
    print(i)
# 输出:0 2 4 6 8

# 反向遍历
for i in range(10, 0, -1):  # 从10递减到1
    print(i)
# 输出:10 9 8 7 6 5 4 3 2 1

enumerate()函数

enumerate()函数用于同时获取元素的索引和值。

# 使用enumerate遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for index, fruit in enumerate(fruits):
    print(f"索引{index}{fruit}")

# 指定起始索引
for index, fruit in enumerate(fruits, 1):
    print(f"第{index}个水果:{fruit}")

循环控制语句

循环控制语句用于改变循环的执行流程。

break语句

break语句用于立即退出循环。

# 在for循环中使用break
for i in range(10):
    if i == 5:
        break
    print(i)
# 输出:0 1 2 3 4

# 在while循环中使用break
count = 0
while True:
    if count >= 5:
        break
    print(count)
    count += 1
# 输出:0 1 2 3 4

continue语句

continue语句用于跳过当前循环的剩余部分,直接进入下一次循环。

# 在for循环中使用continue
for i in range(10):
    if i % 2 == 0:  # 跳过偶数
        continue
    print(i)
# 输出:1 3 5 7 9

# 在while循环中使用continue
count = 0
while count < 10:
    count += 1
    if count % 2 == 0:  # 跳过偶数
        continue
    print(count)
# 输出:1 3 5 7 9

循环中的else子句

循环可以有else子句,当循环正常结束(没有被break中断)时执行。

for循环中的else

# 正常结束的for循环
for i in range(5):
    print(i)
else:
    print("循环正常结束")
# 输出:0 1 2 3 4
#      循环正常结束

# 被break中断的for循环
for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("循环正常结束")
# 输出:0 1 2
#      (else子句不会执行)

while循环中的else

# 正常结束的while循环
count = 0
while count < 3:
    print(count)
    count += 1
else:
    print("循环正常结束")
# 输出:0 1 2
#      循环正常结束

# 被break中断的while循环
count = 0
while count < 5:
    if count == 3:
        break
    print(count)
    count += 1
else:
    print("循环正常结束")
# 输出:0 1 2
#      (else子句不会执行)

综合应用示例

# 猜数字游戏
import random

def guess_number_game():
    """猜数字游戏示例"""
    secret_number = random.randint(1, 100)
    attempts = 0
    max_attempts = 7
    
    print("欢迎来到猜数字游戏!")
    print("我想了一个1到100之间的数字,你有7次机会猜中它。")
    
    while attempts < max_attempts:
        try:
            guess = int(input(f"第{attempts + 1}次猜测,请输入你的数字:"))
            attempts += 1
            
            if guess == secret_number:
                print(f"恭喜你!你在第{attempts}次猜中了数字{secret_number}!")
                break
            elif guess < secret_number:
                print("太小了,请猜大一点。")
            else:
                print("太大了,请猜小一点。")
                
            # 显示剩余次数
            remaining = max_attempts - attempts
            if remaining > 0:
                print(f"你还有{remaining}次机会。")
                
        except ValueError:
            print("请输入一个有效的数字。")
            attempts -= 1  # 无效输入不计入尝试次数
    else:
        print(f"游戏结束!正确答案是{secret_number}。")

# 九九乘法表
def multiplication_table():
    """打印九九乘法表"""
    for i in range(1, 10):
        for j in range(1, i + 1):
            print(f"{j}×{i}={i*j}", end="\t")
        print()  # 换行

# 调用函数
multiplication_table()

# 质数判断
def is_prime(n):
    """判断一个数是否为质数"""
    if n < 2:
        return False
    
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

# 打印1到100之间的所有质数
print("1到100之间的质数:")
primes = []
for num in range(1, 101):
    if is_prime(num):
        primes.append(num)

# 每行打印10个质数
for i, prime in enumerate(primes):
    print(prime, end="\t")
    if (i + 1) % 10 == 0:
        print()  # 换行

总结

本篇教程详细介绍了Python中的条件语句和循环语句,包括if、if-else、if-elif-else语句,以及while循环和for循环。我们还学习了循环控制语句(break、continue)和循环中的else子句。

掌握这些控制结构对于编写复杂的程序至关重要,它们是构建程序逻辑的基础。通过合理使用这些结构,我们可以让程序根据不同的条件执行不同的操作,并重复执行某些任务。


Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐