python循环代码
使用 for 循环遍历列表:
python# 定义一个列表
numbers = [1, 2, 3, 4, 5]
# 使用 for 循环遍历列表中的元素
for num in numbers:
print(num)
使用 for 循环遍历字典的键值对:
python# 定义一个字典
person = {"name": "John", "age": 30, "city": "New York"}
# 使用 for 循环遍历字典的键值对
for key, value in person.items():
print(key + ":", value)
使用 while 循环计数器输出直到达到特定条件:
python# 定义一个计数器变量
count = 0
# 使用 while 循环打印数字,直到 count 变量的值大于等于 5
while count < 5:
print("Count is", count)
count += 1 # 增加计数器的值
这些代码演示了 Python 中使用 for 和 while 循环的基本示例。你可以根据自己的需求修改这些代码,实现更复杂的逻辑。