循环控制:Python for循环和while循环案例
在Python编程中,循环结构提供了反复执行代码块的方法。这里我们将介绍两种主要的循环类型:for循环和while循环。
for循环:
- 适用于已知次数或长度的迭代。
示例:
# 遍历一个列表
for item in ['apple', 'banana', 'cherry']:
print(item)
# 遍历一个字典
dictionary = {'name': 'Tom', 'age': 20}
for key, value in dictionary.items():
print(f"{key}: {value}")
while循环:
- 在循环条件满足时重复执行。
示例:
# 当数字小于10时循环
count = 0
while count < 10:
print("This is loop number: ", count + 1)
count += 1
# 只要变量未改变,就一直循环
variable = "change"
while variable == "change":
process()
variable = input("Enter new value: ")
以上是Python中for循环和while循环的简单示例。在实际编程中,根据需要选择合适的循环类型。
还没有评论,来说两句吧...