Python中的循环结构主要用于重复执行一段代码,直到满足某个条件为止。Python主要有两种循环结构:
for
循环和
while
循环。
二者如何选择使用可参考: for循环和while循环的区别和应用场景
1. for循环
for
循环在Python中通常用于遍历序列(如列表、元组、字符串)或其他可迭代对象(如字典、集合等)。for
循环的基本结构如下:
for 变量名 in 可迭代对象:
# 循环体,每次迭代都会执行这里的代码块
代码块
代码实操
遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
输出结果:
apple
banana
cherry
遍历字典的键
person = {"name": "Alice", "age": 30, "city": "New York"}
for key in person:
print(key)
输出结果:
name
age
city
遍历字典的键值对
person = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in person.items():
print(f"{key}: {value}")
输出结果:
name: Alice
age: 30
city: New York
2. while循环
while
循环用于在满足特定条件时重复执行代码块。只要条件为真(True),就会一直执行循环体中的代码。while
循环的基本结构如下:
while 条件表达式:
# 循环体,当条件为真时执行这里的代码块
代码块
代码实操
打印从1到5的数字
count = 1
while count <= 5:
print(count)
count += 1
输出结果:
1
2
3
4
5
无限循环(通常使用break
或return
来跳出)
while True:
user_input = input("请输入一个数字(输入'q'退出):")
if user_input.lower() == 'q':
break
else:
print(f"你输入了:{user_input}")
这个代码会一直要求用户输入数字,直到用户输入’q’为止。
希望这些解释和代码实操能帮助你更好地理解Python中的for
循环和while
循环。