python之for循环的简单用法-CSDN博客
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
python之for循环的简单用法
简介
Python中的for循环是一种用于遍历可迭代对象如列表元组字典字符串文件对象等的循环结构。它通常用于迭代序列中的元素或者对可迭代对象中的元素执行相同的操作。
基本的for循环的语法如下
for variable in iterable:
# 操作代码块
在这里variable是用来临时存储可迭代对象中的每一个元素的变量iterable是要遍历的可迭代对象。在每次循环迭代中iterable中的下一个元素将被赋值给variable。
例子
1遍历列表
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
2遍历字典
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
for key, value in person.items():
print(key, ":", value)
3遍历字符串
message = "Hello, world!"
for char in message:
print(char)
4使用range()函数生成一系列数字
for num in range(1, 6):
print(num)
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |