Python学习中使用循环(for, while)

在Python编程语言中,循环是一个非常重要的概念,可以帮助我们在代码中重复执行某些操作。Python支持两种主要的循环结构:for 循环和 while 循环。

1. for 循环

for 循环用于遍历一个序列(如列表、元组、字符串)或其他可迭代对象(如字典、集合)。它的基本语法如下:

python 复制代码
for variable in iterable:
    # 执行代码块

其中,variable 是一个变量,它将在每次迭代中被赋予 iterable 中的下一个值,iterable 是一个可迭代对象。以下是一些示例:

示例 1:遍历列表

python 复制代码
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

输出:

bash 复制代码
apple
banana
cherry

示例 2:遍历字符串

python 复制代码
for char in 'hello':
    print(char)

输出:

bash 复制代码
h
e
l
l
o

示例 3:使用 range() 函数

range() 函数用于生成一个数值序列。它通常与 for 循环一起使用。基本语法如下:

python 复制代码
for i in range(start, stop, step):
    # 执行代码块
  • start:序列的起始值,默认为0。
  • stop:序列的结束值(不包含在序列中)。
  • step:步长,默认为1。

示例:

python 复制代码
for i in range(5):
    print(i)

输出:

bash 复制代码
0
1
2
3
4

示例 4:遍历字典

python 复制代码
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
for key, value in student.items():
    print(f'{key}: {value}')

输出:

vbnet 复制代码
name: John
age: 25
courses: ['Math', 'CompSci']

示例 5:嵌套 for 循环

python 复制代码
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for item in row:
        print(item, end=' ')
    print()

输出:

bash 复制代码
1 2 3 
4 5 6 
7 8 9 

2. while 循环

while 循环在给定的条件为真时,重复执行目标语句。它的基本语法如下:

python 复制代码
while condition:
    # 执行代码块

其中,condition 是一个表达式,当其为真时,执行代码块。下面是一些示例:

示例 1:简单 while 循环

python 复制代码
i = 0
while i < 5:
    print(i)
    i += 1

输出:

bash 复制代码
0
1
2
3
4

示例 2:用户输入

python 复制代码
user_input = ''
while user_input.lower() != 'exit':
    user_input = input('Enter something (type "exit" to quit): ')
    print(f'You entered: {user_input}')

示例 3:无限循环和 break

python 复制代码
while True:
    user_input = input('Enter something (type "exit" to quit): ')
    if user_input.lower() == 'exit':
        break
    print(f'You entered: {user_input}')

示例 4:continue 语句

python 复制代码
i = 0
while i < 10:
    i += 1
    if i % 2 == 0:
        continue
    print(i)

输出:

bash 复制代码
1
3
5
7
9

3. for 循环和 while 循环的区别

  • 使用场景for 循环通常用于遍历固定长度的序列,而 while 循环适用于未知长度的循环或需要在满足特定条件时终止的循环。
  • 可读性for 循环通常更简洁,更易读,尤其是在处理序列时。while 循环在处理复杂条件时更灵活。
  • 性能 :在许多情况下,for 循环的性能可能稍好,因为它们在许多情况下可以更有效地进行优化。

4. 循环中的常见问题

无限循环

无限循环是指循环条件永远为真的循环。通常是由于条件未正确更新导致的。示例:

python 复制代码
i = 0
while i < 5:
    print(i)
    # 缺少 i += 1,导致 i 永远为 0

breakcontinue

  • break:立即终止循环。
  • continue:跳过当前迭代,继续下一次迭代。

示例:

python 复制代码
for i in range(10):
    if i == 5:
        break
    print(i)

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

嵌套循环中的 break

在嵌套循环中使用 break 只会终止内层循环。示例:

python 复制代码
for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print(f'i={i}, j={j}')

输出:

css 复制代码
i=0, j=0
i=1, j=0
i=2, j=0

循环与条件语句结合

python 复制代码
for i in range(1, 11):
    if i % 2 == 0:
        print(f'{i} 是偶数')
    else:
        print(f'{i} 是奇数')

输出:

bash 复制代码
1 是奇数
2 是偶数
3 是奇数
4 是偶数
5 是奇数
6 是偶数
7 是奇数
8 是偶数
9 是奇数
10 是偶数

5. 实践案例

案例 1:计算列表中所有元素的和

python 复制代码
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
    total += num
print(f'列表元素的和为: {total}')

案例 2:找出列表中的最大值

python 复制代码
numbers = [3, 41, 12, 9, 74, 15]
max_num = numbers[0]
for num in numbers:
    if num > max_num:
        max_num = num
print(f'列表中的最大值是: {max_num}')

案例 3:使用 while 循环实现猜数字游戏

python 复制代码
import random

secret_number = random.randint(1, 100)
guess = None
attempts = 0

while guess != secret_number:
    guess = int(input('猜一个 1 到 100 之间的数字: '))
    attempts += 1
    if guess < secret_number:
        print('猜低了')
    elif guess > secret_number:
        print('猜高了')
    else:
        print(f'恭喜你,猜对了!你一共猜了 {attempts} 次。')

案例 4:生成乘法表

python 复制代码
for i in range(1, 10):
    for j in range(1, 10):
        print(f'{i} x {j} = {i * j}', end='\t')
    print()

输出:

python 复制代码
1 x 1 = 1	1 x 2 = 2	1 x 3 = 3	1 x 4 = 4	1 x 5 = 5	1 x 6 = 6	1 x 7 = 7	1 x 8 = 8	1 x 9 = 9	
2 x 1 = 2	2 x 2 = 4	2 x 3 = 6	2 x 4 = 8	2 x 5 = 10	2 x 6 = 12	2 x 7 = 14	2 x 8 = 16	2 x 9 = 18	
3 x 1 = 3	3 x 2 = 6	3 x 3 = 9	3 x 4 = 12	3 x 5 = 15	3 x 6 = 18	3 x 7 = 21	3 x 8 = 24	3 x 9 = 27	
4 x 1 = 4	4 x 2 = 8	4 x 3 = 12	4 x 4 = 16	4 x 5 = 20	4 x 6 = 24	4 x 7 = 28	4 x 8 = 32	4 x 9 = 36	
5 x 1 = 5	5 x 2 = 10	5 x 3 = 15	5 x 4 = 20	5 x 5 = 25	5 x 6 = 30	5 x 7 = 35	5 x 8 = 40	5 x 9 = 45	
6 x 1 = 6	6 x 2 = 12	6 x 3 = 18	6 x 4 = 24	6 x 5 = 30	6 x 6 = 36	6 x 7 = 42	6 x 8 = 48	6 x 9 = 54	
7 x 1 = 7	7 x 2 = 14	7 x 3 = 21	7 x 4 = 28	7 x 5 = 35	7 x 6 = 42	7 x 7 = 49	7 x 8 = 56	7 x 9 = 63	
8 x 1 = 8	8 x 2 = 16	8 x 3 = 24	8 x 4 = 32	8 x 5 = 40	8 x 6 = 48	8 x 7 = 56	8 x 8 = 64	8 x 9 = 72	
9 x 1 = 9	9 x 2 = 18	9 x 3 = 27	9 x 4 = 36	9 x 5 = 45	9 x 6 = 54	9 x 7 = 63	9 x 8 = 72	9 x 9 = 81	

案例 5:统计字符串中每个字符的出现频率

python 复制代码
text = 'hello world'
char_count = {}

for char in text:
    if char in char_count:
        char_count[char] += 1
    else:
        char_count[char] = 1

for char, count in char_count.items():
    print(f'{char}: {count}')

输出:

Matlab 复制代码
h: 1
e: 1
l: 3
o: 2
 : 1
w: 1
r: 1
d: 1

循环结构是Python编程中的基本概念,for 循环和 while 循环各有其适用场景和优势。for 循环适用于遍历已知长度的序列,而 while 循环则在处理需要满足特定条件时特别有用。理解并掌握这两种循环的用法,可以大大提高代码的可读性和效率。

相关推荐
蒸蒸yyyyzwd9 分钟前
cpp选手备战秋招学习笔记day17
笔记·学习
陈天伟教授1 小时前
【30天学会机械制图 第15 天】项目四 学会看零件图 任务1 学习零件的基本表达方法 (1)
学习·工程制图·机械制图
小张帅三代1 小时前
yolo基础学习笔记
笔记·学习·yolo
zttbee1 小时前
vue学习(白话功能版)
前端·vue.js·学习·前端框架
ouynagda1 小时前
Linux 进程与线程学习笔记
linux·笔记·学习
手握风云-2 小时前
一条消息的旅程:RabbitMQ 学习与实践(四)
学习
小弥儿14 小时前
GitHub今日热榜 | 2026-08-26:AI 大脑与知识管理扎堆
人工智能·学习·开源·github
荷蒲14 小时前
【小白量化Qbuddy】利用AI学习中文Python
人工智能·python·学习
中科高级技工学校14 小时前
乌鲁木齐中医康复学习经历分享
大数据·学习