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)
相关推荐
汤姆小白11 小时前
01-环境搭建与项目导览
人工智能·python·机器学习·numpy
科技道人15 小时前
记录 默认置灰/禁用 app ‘Search Engine Selector‘ 的disable按钮
开发语言·前端·javascript
向日的葵00617 小时前
langchain的Tools教程(三)
python·langchain·tools
逝水无殇18 小时前
C# 异常处理详解
开发语言·后端·c#
言乐619 小时前
Python实现可运行解密游戏游戏框架
python·游戏·小程序·游戏程序·关卡设计
YUS云生19 小时前
Python学习笔记·第31天:FastAPI入门——路由、路径参数、查询参数与请求体
笔记·python·学习
玖玥拾19 小时前
C# 语言进阶(十五)C# 游戏服务端 MySQL 数据库
服务器·开发语言·网络·数据库·mysql·c#
智写-AI19 小时前
真实有效的免费降英文AI工具服务商
人工智能·python
铅笔侠_小龙虾19 小时前
Rust 学习目录
开发语言·学习·rust
yuhuofei202120 小时前
【Python入门】了解掌握Python中函数的基本使用
python