python中for循环用法

1、在python中完整的for语法如下 

# for 变量 in 集合:
#     循环代码
# else :
#     没有通过的break退出循环,结束后会执行代码

2、应用场景

  在迭代变量嵌套的数据类型时,列表【数组】中包括多个字典【键值对存放的值:用{key:value}】

  需求:要判断某一个字典中是否存在要遍历的值

    如果存在,提示并退出循环,可以用break

    如果不存在,在整个循环结束后退出循环,希望得到一个统一的提示

# -*- coding: utf-8 -*-
studens = [ {"name":"阿土", "age":22, "gender":"man", "height":2.0, "weight":30 }, {"name": "阿狗", "age": 20, "gender": "man", "height": 1.7, "weight": 60 } ] find_name = "阿土" for stu_dict in studens: print(stu_dict) print(type(stu_dict)) #<class 'dict'> #判断当前遍历的字典中姓名是否为find_name if stu_dict["name"] == find_name: print("找到了") break else: print("不存在") print("结束寻址")

运行结果:

{'name': '阿土', 'age': 22, 'gender': 'man', 'height': 2.0, 'weight': 30}
<class 'dict'>
找到了
结束寻址

注意事项:

1、如果首行代码中未出现# -*- coding: utf-8 -*-    可能出现下面的错误提示

   SyntaxError: Non-UTF-8 code starting with \xc0 in file but no encoding declared

2、studens【a,b】其中students是一个列表;循环得到的每一个元素是字典,如果想要得到字典中的value值,

  可以用如下方法:

for stu_dict in studens:
    print(stu_dict["name"])
    print(stu_dict["age"])
    print(stu_dict["gender"])
    print(stu_dict["height"])

 

posted @ 2023-12-06 19:27  zhang0513  阅读(34)  评论(0编辑  收藏  举报