• Python 学习笔记10 循环语句 For in


    For in 循环主要适用于遍历一个对象中的所有元素。我们可以使用它遍历列表,元组和字典等等。

    其主要的流程如下:(图片来源于: https://www.yiibai.com/python/python_for_loop.html

     使用For遍历一个列表:

    peoples = ['Ralf', 'Clark', 'Leon', 'Terry']
    for people in peoples:
        print(people)
    
    '''
    输出:
    Ralf
    Clark
    Leon
    Terry
    '''

    使用For in 遍历一个字典:

    ralf = {'name': 'Ralf', 'sex': 'male', 'height': '188'}
    
    for key, value in ralf.items():
        print(key + ":" + value)
    
    '''
    输出:
    name:Ralf
    sex:male
    height:188
    '''

    在For 循环中,我们可以使用 break, 在遇到特殊条件时,中断循环操作:

    peoples = ['Ralf', 'Clark', 'Leon', 'Terry', 'Mary']
    for people in peoples:
        if people == 'Terry':
            break
        print(people)
    
    '''
    输出:
    Ralf
    Clark
    Leon
    '''

    使用continue在for中继后继续下一轮的循环。

    peoples = ['Ralf', 'Clark', 'Leon', 'Terry', 'Mary']
    for people in peoples:
        if people == 'Terry':
            continue
        print(people)
    
    '''
    输出:
    Ralf
    Clark
    Leon
    Mary
    '''

    For 循环中也可以使用else结构,当循环结束时执行特定语句,但是break中断时,else里面数据不会被执行:

    peoples = ['Ralf', 'Clark', 'Leon', 'Terry', 'Mary']
    for people in peoples:
        print(people)
    else:
        print('Loop is end')
    '''
    输出:
    Ralf
    Clark
    Leon
    Terry
    Mary
    Loop is end
    '''
    
    
    peoples = ['Ralf', 'Clark', 'Leon', 'Terry', 'Mary']
    for people in peoples:
        if people == 'Terry':
            break
        print(people)
    else:
        print('Loop is end')
    
    '''
    输出:
    Ralf
    Clark
    Leon
    '''
  • 相关阅读:
    Linux基本命令
    IDEA实用插件
    Windows常用快捷键
    IDEA常用快捷键
    OOP三大特性之多态
    IDEA里配置SSM框架,配置没问题却报404错误
    Tomcat的80端口被占用问题_解决方案
    基于SpringBoot开发
    java数据结构--线性表
    代码优化设计(一)
  • 原文地址:https://www.cnblogs.com/wanghao4023030/p/10732381.html
Copyright © 2020-2023  润新知