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)
相关推荐
星云穿梭5 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵5 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠11 小时前
大模型之LangGraph技术体系
python·llm
hboot1 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780511 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780511 天前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠1 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3101 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫1 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔2 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试