python中for循环写法
时间: 2024-03-02 08:46:55 浏览: 147
python中的for循环
在Python中,for循环用于遍历可迭代对象(如列表、元组、字符串等)中的元素。以下是Python中for循环的几种常见写法:
1. 遍历列表:
```python
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
```
2. 遍历元组:
```python
numbers = (1, 2, 3, 4, 5)
for number in numbers:
print(number)
```
3. 遍历字符串:
```python
message = "Hello, World!"
for char in message:
print(char)
```
4. 遍历字典的键:
```python
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for key in person:
print(key)
```
5. 遍历字典的值:
```python
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for value in person.values():
print(value)
```
6. 遍历字典的键值对:
```python
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for key, value in person.items():
print(key, value)
```
7. 使用range函数进行循环:
```python
for i in range(1, 6):
print(i)
```
以上是Python中for循环的几种常见写法,可以根据具体需求选择适合的方式进行循环遍历。
阅读全文