python之for循环的简单用法

python之for循环的简单用法

简介

Python中的for循环是一种用于遍历可迭代对象(如列表,元组,字典,字符串,文件对象等)的循环结构。它通常用于迭代序列中的元素,或者对可迭代对象中的元素执行相同的操作。

基本的for循环的语法如下:

python 复制代码
for variable in iterable:  
    # 操作代码块

在这里,variable是用来临时存储可迭代对象中的每一个元素的变量,iterable是要遍历的可迭代对象。在每次循环迭代中,iterable中的下一个元素将被赋值给variable。

例子

1)遍历列表:

python 复制代码
fruits = ['apple', 'banana', 'cherry']  
for fruit in fruits:  
    print(fruit)

2)遍历字典:

python 复制代码
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}  
for key, value in person.items():  
    print(key, ":", value)

3)遍历字符串:

python 复制代码
message = "Hello, world!"  
for char in message:  
    print(char)

4)使用range()函数生成一系列数字:

python 复制代码
for num in range(1, 6):  
    print(num)
相关推荐
金銀銅鐵4 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup119 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0011 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵13 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf13 小时前
Agent 流程编排
后端·python·agent
copyer_xyf14 小时前
Agent RAG
后端·python·agent
copyer_xyf14 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf14 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python