循环python案例
时间: 2024-04-23 11:19:12 浏览: 76
当然,我可以给你介绍一些Python中的循环案例。Python提供两种主要的循环结构:for循环和while循环。
1. for循环案例:
```python
# 打印列表中的元素
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# 计算列表中所有元素的和
numbers = [1, 2, 3, 4, 5]
total = 0
for number in numbers:
total += number
print("总和为:", total)
# 遍历字典中的键值对
student_scores = {"Tom": 80, "Jerry": 90, "Alice": 95}
for name, score in student_scores.items():
print(name, "的分数是", score)
```
2. while循环案例:
```python
# 计算1到10的累加和
total = 0
num = 1
while num <= 10:
total += num
num += 1
print("总和为:", total)
# 猜数字游戏
secret_number = 42
guess = int(input("猜一个数字: "))
while guess != secret_number:
if guess < secret_number:
print("猜小了!")
else:
print("猜大了!")
guess = int(input("再猜一个数字: "))
print("恭喜你,猜对了!")
```
阅读全文