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)
相关推荐
明月_清风6 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风6 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风1 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风1 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly2 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling2 天前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook2 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风2 天前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风2 天前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python