python中for循环的用法
时间: 2023-09-15 16:20:55 浏览: 56
Python中的for循环可以遍历任何可迭代对象,如列表、元组、字符串等。其语法如下:
```python
for 变量名 in 可迭代对象:
执行语句
```
其中,变量名是在循环中每次迭代时被赋值的变量,可迭代对象是被遍历的对象。
示例代码:
```python
# 遍历列表
lst = [1, 2, 3, 4, 5]
for num in lst:
print(num)
# 遍历元组
tup = (6, 7, 8, 9, 10)
for num in tup:
print(num)
# 遍历字符串
str = "Hello, World!"
for ch in str:
print(ch)
```
输出:
```
1
2
3
4
5
6
7
8
9
10
H
e
l
l
o
,
W
o
r
l
d
!
```
相关问题
python中for循环用法
在 Python 中,for 循环用于迭代序列(列表、元组、字符串等)中的元素,或其他可迭代对象,例如字典中的键或文件中的行。
使用 for 循环的一般语法结构如下:
```python
for var in sequence:
# 迭代执行的代码块
```
其中,`var` 是迭代序列中的当前元素,`sequence` 是要迭代的序列。执行代码块的次数取决于序列中元素的数量。
例如,遍历列表:
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
输出:
```
apple
banana
cherry
```
遍历元组:
```python
colors = ("red", "green", "blue")
for color in colors:
print(color)
```
输出:
```
red
green
blue
```
遍历字符串:
```python
message = "Hello, world!"
for char in message:
print(char)
```
输出:
```
H
e
l
l
o
,
w
o
r
l
d
!
```
遍历字典中的键:
```python
person = {"name": "Alice", "age": 25}
for key in person:
print(key)
```
输出:
```
name
age
```
如果要同时遍历字典中的键和值,可以使用 `items()` 方法:
```python
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(key, ":", value)
```
输出:
```
name : Alice
age : 25
```
Python中for循环的用法
在 Python 中,for 循环可以用于遍历任何可迭代对象,如列表、元组、字符串、字典等。for 循环的语法形式如下:
```python
for 变量 in 序列:
循环体语句
else:
循环结束之后执行的语句
```
其中,`变量` 表示在每次循环中,从序列中取出的一个元素,`序列` 表示要遍历的序列,`循环体语句` 表示需要执行的循环操作语句。`else` 语句是可选的,如果存在,则在循环结束后执行。
举个例子,我们可以使用 for 循环遍历一个列表:
```python
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
```
输出:
```
apple
banana
orange
```
我们也可以使用 for 循环遍历一个字典:
```python
person = {'name': 'Tom', 'age': 18, 'gender': 'male'}
for key, value in person.items():
print(key, ':', value)
```
输出:
```
name : Tom
age : 18
gender : male
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)