python基础训练-for循环

本文详细介绍了Python中for、while、嵌套循环、条件语句等20个实例,包括列表操作、字典遍历、文件读取等,旨在帮助新手快速理解和掌握循环结构,为AI时代的编程打下坚实基础。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

适应人群:学习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 += i
    i += 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:
        continue
    print(i)
使用 break 跳出循环:
for i in range(1, 11):
    if i == 5:
        break
    print(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")
        break
    except 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")
        break
    elif 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中的循环概念。

为了在Windows安装ADB工具,你可以按照以下步骤进行操作: 1. 首先,下载ADB工具包并解压缩到你自定义的安装目录。你可以选择将其解压缩到任何你喜欢的位置。 2. 打开运行窗口,可以通过按下Win+R键来快速打开。在运行窗口中输入"sysdm.cpl"并按下回车键。 3. 在系统属性窗口中,选择"高级"选项卡,然后点击"环境变量"按钮。 4. 在环境变量窗口中,选择"系统变量"部分,并找到名为"Path"的变量。点击"编辑"按钮。 5. 在编辑环境变量窗口中,点击"新建"按钮,并将ADB工具的安装路径添加到新建的路径中。确保路径正确无误后,点击"确定"按钮。 6. 返回到桌面,打开命令提示符窗口。你可以通过按下Win+R键,然后输入"cmd"并按下回车键来快速打开命令提示符窗口。 7. 在命令提示符窗口中,输入"adb version"命令来验证ADB工具是否成功安装。如果显示版本信息,则表示安装成功。 这样,你就成功在Windows安装ADB工具。你可以使用ADB工具来执行各种操作,如枚举设备、进入/退出ADB终端、文件传输、运行命令、查看系统日志等。具体的操作方法可以参考ADB工具的官方文档或其他相关教程。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* [windows环境安装adb驱动](https://blog.youkuaiyun.com/zx54633089/article/details/128533343)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Windows安装使用ADB简单易懂教程](https://blog.youkuaiyun.com/m0_37777700/article/details/129836351)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值