python 循环例子
时间: 2023-07-06 08:35:49 浏览: 41
以下是一个 Python 的 for 循环例子:
```python
# 打印出列表中的每个元素
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
输出:
```
apple
banana
cherry
```
这个例子中,我们使用 for 循环遍历了一个列表,打印出了列表中的每个元素。在每次循环中,变量 `fruit` 都会被赋值为列表中的一个元素。
相关问题
python循环语句例子
以下是几个常见的 Python 循环语句的例子:
1. 使用 `for` 循环遍历列表中的元素:
```python
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
```
输出:
```
apple
banana
cherry
```
2. 使用 `while` 循环计算某个条件下的累加和:
```python
sum = 0
num = 1
while num <= 10:
sum += num
num += 1
print("Sum =", sum)
```
输出:
```
Sum = 55
```
3. 使用 `for` 循环打印一个范围内的数字:
```python
for i in range(1, 5):
print(i)
```
输出:
```
1
2
3
4
```
这些例子展示了 `for` 和 `while` 循环的基本用法。你可以根据具体的需求来选择合适的循环类型,并在循环体中执行相应的操作。
python while循环例子
以下是一个简单的 Python while 循环的例子:
```python
count = 0
while count < 5:
print("Count:", count)
count += 1
```
在这个例子中,我们使用了一个变量 `count` 来跟踪循环的次数。while 循环的条件是 `count < 5`,只要条件为真,循环就会一直执行。
在循环体内部,我们打印出当前的 `count` 值,并且每次循环结束后将 `count` 值增加 1。这样,循环会执行 5 次,当 `count` 达到 5 时,条件不再满足,循环终止。
这是一个简单的示例,你可以根据需要在循环体内添加更多的逻辑和操作。