在Python编程中,`for`循环是一种非常强大且常用的控制结构,用于遍历序列(如列表、元组、字符串等)或其他可迭代对象。以下是`for`循环的基本用法和一些常见场景:
基本语法
```python
for 变量 in 可迭代对象:
循环体代码
```
`变量`:用于存储可迭代对象中当前元素的变量。
`可迭代对象`:可以是列表、元组、字符串、字典、集合等数据类型,甚至是自定义的可迭代类的实例。
示例
遍历列表
```python
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(f"我喜欢吃{fruit}")
```
遍历字符串
```python
for char in "Python":
print(char)
```
带索引的遍历
```python
fruits = ["苹果", "香蕉", "橙子"]
for index, fruit in enumerate(fruits):
print(f"第{index+1}个水果是:{fruit}")
```
遍历字典
```python
scores = {"小明": 90, "小红": 95, "小华": 88}
for name, score in scores.items():
print(f"{name}的分数是:{score}")
```
注意事项
使用`for`循环遍历字典时,如果只写`for key`,则只能遍历字典的键。
`range()`函数可以与`for`循环搭配使用,生成一系列数字。
额外提示
`range(start, stop, step)`函数可以生成一个整数序列,其中`step`参数可以控制步长。
`enumerate()`函数可以同时获取索引和值。
实战示例
编写一个小程序,统计班级成绩的平均分:
```python
scores = {"Alice": 90, "Bob": 85, "Charlie": 92}
total_score = 0
num_students = 0
for name, score in scores.items():
print(f"{name}的分数是{score}")
total_score += score
num_students += 1
average_score = total_score / num_students
print(f"班级平均分是: {average_score}")
```
通过这些示例和解释,你应该能够更好地理解Python中`for`循环的用法,并在实际编程中有效地应用它。