一、for 循环
for 循环的语法格式如下:
for 迭代变量 in 字符串|列表|元组|字典|集合:
代码块
迭代变量用于存放从序列类型变量中读取出来的元素,所以一般不会在循环中对迭代变量手动赋值; 代码块指的是具有相同缩进格式的多行代码(和 while 一样),由于和循环结构联用,因此代码块又称为循环体。 ![在这里插入图片描述](https://img-blog.csdnimg.cn/a6a05b1164d34adfad54387a108172a4.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAd8Ky5aSn5aSn,size_20,color_FFFFFF,t_70,g_se,x_16)
二、用法
1.for 循环遍历数值
print("计算1+2+3+...+100的结果为:")
sum = 0
for i in range(100+1):
sum = sum + i
print(sum)
![在这里插入图片描述](https://img-blog.csdnimg.cn/3293dd45900e43c481499a90d3204237.png)
2.for 循环遍历字符串
str1 = "welcome to FPGA"
for ch in str1:
print(ch,end="")
![在这里插入图片描述](https://img-blog.csdnimg.cn/da865d9e2482467e98870178e26aaf82.png)
3.for 循环遍历列表和元组
当用 for 循环遍历 list 列表或者 tuple 元组时,其迭代变量会先后被赋值为列表或元组中的每个元素并执行一次循环体。
#my_list = [1,2,3,4,5]
my_tuple = (1,2,3,4,5)
for element in my_tuple:
print("element:",element)
![在这里插入图片描述](https://img-blog.csdnimg.cn/8d9dfca89a7c4defa0c7e6ed21ea73ec.png)
4.for 循环遍历字典
在使用 for 循环遍历字典时,经常会用到和字典相关的 3 个方法,即 items()、keys() 以及 values()
keys()
当然,如果使用 for 循环直接遍历字典,则迭代变量会被先后赋值为每个键值对中的键 代码如下:
my_dic = {
"Name":"Tom",\
"Age":"24",\
"Sex":"boy"
}
for element in my_dic:
print("element:",element)
![在这里插入图片描述](https://img-blog.csdnimg.cn/6046370a6c58479d992799022bfc00b7.png)
因此,直接遍历字典,和遍历字典 keys() 方法的返回值是相同的。 代码如下:
my_dic = {
"Name":"Tom",\
"Age":"24",\
"Sex":"boy"
}
# for element in my_dic:
# print("element:",element)
for element in my_dic.keys():
print("element:",element)
![在这里插入图片描述](https://img-blog.csdnimg.cn/82e7eebee45c459d8ea52342c5325e19.png)
values()
my_dic = {
"Name":"Tom",\
"Age":"24",\
"Sex":"boy"
}
for element in my_dic.values():
print("element:",element)
![在这里插入图片描述](https://img-blog.csdnimg.cn/71c429be9a2c40019ab658d2049ad517.png)
items()
Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。
语法 items()方法语法:
dict.items() 参数: NA。 返回值: 返回可遍历的(键, 值) 元组数组。
my_dic = {
"Name":"Tom",\
"Age":"24",\
"Sex":"boy"
}
for element in my_dic.items():
print("element:",element)
![在这里插入图片描述](https://img-blog.csdnimg.cn/71979ddf222a401cb8caac0e1ee1dfb8.png)
|