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)
相关推荐
aq553560012 小时前
四大编程语言对比:PHP、Python、Java、易语言
java·python·php
qq_2837200512 小时前
Python GIL 底层实现与高并发突破实战
python·性能优化·高并发·全局锁
橙露12 小时前
Python 对接 API:自动化拉取、清洗、入库一站式教程
开发语言·python·自动化
Omigeq13 小时前
1.4 - 曲线生成轨迹优化算法(以BSpline和ReedsShepp为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·算法·机器人
2301_8084143813 小时前
自动化测试的实施
开发语言·python
无限码力13 小时前
华为OD技术面真题 - Python开发 - 4
python·华为od·华为od技术面真题·华为od面试八股文·华为od面试真题·华为odpython开发真题·华为od技术面题目
波波00713 小时前
写出稳定C#系统的关键:不可变性思想解析
开发语言·c#·wpf
dr_yingli13 小时前
fMRI(3-1)报告(个体化报告)生成器说明
开发语言·matlab
hrhcode13 小时前
【java工程师快速上手go】一.Go语言基础
java·开发语言·golang
l1t13 小时前
用wsl自带的python 3.10下载适用于3.12的pandas版本结合uv安装python 3.12模拟离线安装场景
python·pandas·uv