python中for循环简单例题
时间: 2024-08-12 10:05:08 浏览: 95
在Python中,`for`循环是一种常用的迭代结构,用于遍历序列、列表、元组、字符串或其他支持迭代的对象中的元素。下面是一个简单的例子:
```python
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
相关问题
python for循环的例题
以下是一个Python for循环的例题:
假设有一个列表,需要将其中的每个元素都打印出来,可以使用for循环来实现:
```python
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
```
上述代码中,首先定义了一个列表my_list,然后使用for循环遍历该列表中的每个元素,将每个元素打印出来。在for循环中,item是一个临时变量,用于存储当前遍历到的元素。
python for循环的经典例题
以下是一个经典的Python for循环例题,用于计算100以内所有奇数的和:
```python
sum = 0
for i in range(1, 101, 2):
sum += i
print(sum)
```
输出结果为:2500
解释:range(1, 101, 2)表示从1开始,每次增加2,直到101结束。因此,这个循环将遍历所有100以内的奇数,并将它们相加。
阅读全文
相关推荐
















