python怎么使用for循环遍历
时间: 2024-02-29 10:50:19 浏览: 57
Python-遍历列表-for循环
5星 · 资源好评率100%
在Python中,使用for循环可以遍历各种可迭代对象,如列表、元组、字符串等。for循环的语法如下:
```python
for 变量 in 可迭代对象:
# 执行的代码块
```
其中,变量是用来存储每次迭代的值的变量名,可迭代对象是需要遍历的对象。
下面是一些示例:
1. 遍历列表:
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
输出:
```
apple
banana
cherry
```
2. 遍历元组:
```python
numbers = (1, 2, 3, 4, 5)
for number in numbers:
print(number)
```
输出:
```
1
2
3
4
5
```
3. 遍历字符串:
```python
message = "Hello, World!"
for char in message:
print(char)
```
输出:
```
H
e
l
l
o
,
W
o
r
l
d
!
```
4. 遍历字典的键值对:
```python
student = {"name": "Alice", "age": 20, "major": "Computer Science"}
for key, value in student.items():
print(key, value)
```
输出:
```
name Alice
age 20
major Computer Science
```
希望以上内容对你有所帮助!
阅读全文