以下是十个简单的 Python for 循环示例,每个示例都包含程序输出和代码讲解:
- 打印列表中的元素:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
输出:
apple
banana
cherry
代码讲解:
这个例子中,我们使用 for
循环遍历列表 fruits
中的每个元素,并打印出来。
- 打印字符串中的字符:
word = "hello"
for char in word:
print(char)
输出:
h
e
l
l
o
代码讲解:
这个例子中,我们使用 for
循环遍历字符串 word
中的每个字符,并打印出来。
- 计算列表中所有元素的总和:
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print("总和为:", total)
输出:
总和为: 15
代码讲解:
这个例子中,我们使用 for
循环遍历列表 numbers
中的每个元素,并累加到 total
变量中,最后输出总和。
- 遍历字典的键值对并打印:
person = {"name": "John", "age": 30, "city": "New York"}
for key, value in person.items():
print(key + ":", value)
输出:
name: John
age: 30
city: New York
代码讲解:
这个例子中,我们使用 for
循环遍历字典 person
中的键值对,并打印键和对应的值。
- 打印数字列表中的偶数:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 == 0:
print(num)
输出:
2
4
6
8
10
代码讲解:
这个例子中,我们使用 for
循环遍历列表 numbers
中的每个元素,并通过条件判断筛选出偶数进行打印。
- 打印九九乘法表:
for i in range(1, 10):
for j in range(1, i+1):
print(j, "*", i, "=", i*j, end="\t")
print()
输出:
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
代码讲解:
这个例子中,我们使用嵌套的 for
循环生成九九乘法表,并在每一行的末尾使用 print()
函数换行。
- 遍历元组并打印索引和值:
tup = ("apple", "banana", "cherry")
for index, value in enumerate(tup):
print("索引", index, ":", value)
输出:
索引 0 : apple
索引 1 : banana
索引 2 : cherry
代码讲解:
这个例子中,我们使用 enumerate()
函数遍历元组 tup
中的每个元素,并打印出其索引和值。
- 使用列表推导式创建新列表:
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num**2 for num in numbers]
print("原始列表:", numbers)
print("平方列表:", squared_numbers)
输出:
原始列表: [1, 2, 3, 4, 5]
平方列表: [1, 4, 9, 16, 25]
代码讲解:
这个例子中,我们使用列表推导式遍历列表 numbers
中的每个元素,并将其平方后存入新的列表 squared_numbers
中。
- 遍历字符串列表并打印每个字符串的长度:
words = ["apple", "banana", "cherry"]
for word in words:
print(word, "的长度为", len(word))
输出:
apple 的长度为 5
banana 的长度为 6
cherry 的长度为 6
代码讲解:
这个例子中,我们使用 for
循环遍历字符串列表 words
中的每个单词,并使用 len()
函数打印出其长度。
了解更多python项目开发,请关注:Python提升课堂