本文主要是介绍python基础训练-for循环,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
适应人群:学习python大概在10-20天,比较勤于动手的同学,比较混沌的新手可以手敲一遍下面这些for循环,在AI时代只有脑子智能,手不生疏,多多运用AI进行语义编程,看懂代码,通过openai教你写代码,帮你解决问题,然后自己多训练代码逻辑,但这一切都是得我们掌握好基础语法。
当我们在学习Python中的循环结构时,可以使用以下20个示例程序来学习不同类型的循环结构以及它们的应用场景:
for 循环打印列表元素:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:print(fruit)
for 循环打印数字范围:
for i in range(5):print(i)
while 循环计算累加和:
sum = 0
i = 1
while i <= 10:sum += ii += 1
print("Sum of first 10 natural numbers:", sum)
嵌套循环打印九九乘法表:
for i in range(1, 10):for j in range(1, 10):print(i, "*", j, "=", i*j)
循环遍历字典元素:
person = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in person.items():print(key, ":", value)
使用 continue 跳过奇数的循环:
for i in range(1, 11):if i % 2 == 1:continueprint(i)
使用 break 跳出循环:
for i in range(1, 11):if i == 5:breakprint(i)
循环中的 else 语句:
for i in range(5):print(i)
else:print("Loop finished without a break")
使用列表推导式创建列表:
squared_numbers = [x**2 for x in range(1, 6)]
print(squared_numbers)
使用列表推导式过滤元素:
numbers = [1, 2, 3, 4, 5]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
使用列表推导式嵌套循环:
coordinates = [(x, y) for x in [1, 2, 3] for y in [3, 5, 7]]
print(coordinates)
使用 zip 函数同时迭代多个列表:
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):print(name, "is", age, "years old")
使用 enumerate 函数同时获取索引和值:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):print("Fruit", index+1, "is", fruit)
使用 sorted 函数对列表进行排序:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
使用 reversed 函数倒序遍历列表:
numbers = [1, 2, 3, 4, 5]
for num in reversed(numbers):print(num)
使用 break 和 else 结合查找质数:
num = 17
for i in range(2, num):if num % i == 0:print(num, "is not a prime number")break
else:print(num, "is a prime number")
使用 while 循环判断输入是否为数字:
while True:try:number = float(input("Enter a number: "))print("You entered a number")breakexcept ValueError:print("That's not a number, try again")
使用 while 循环实现简单的猜数字游戏:
import random
number_to_guess = random.randint(1, 100)
while True:guess = int(input("Guess the number: "))if guess == number_to_guess:print("Congratulations! You guessed the number")breakelif guess < number_to_guess:print("Try higher")else:print("Try lower")
使用 for 循环遍历文件内容:
with open("example.txt", "r") as file:for line in file:print(line.strip())
使用 for 循环处理异常集合:
try:a = 5 / 0
except ZeroDivisionError as e:print("Error:", e)
以上示例涵盖了不同类型的循环结构以及它们在实际编程中的应用,可以帮助我们更好地理解Python中的循环概念。
这篇关于python基础训练-for循环的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!