zoukankan      html  css  js  c++  java
  • 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
    '''
  • 相关阅读:
    2019 SDN阅读作业
    2019 SDN上机第3次作业
    SDN实验2
    SDN
    说好不肝---第五次作业
    [2020BUAA软工助教]助教每周小结(week 8)
    [2020BUAA软工助教]助教每周小结(week 7)
    [2020BUAA软工助教]助教每周小结(week 6)
    [2020BUAA软工助教]助教每周小结(week 5)
    [2020BUAA软工助教]助教每周小结(week 4)
  • 原文地址:https://www.cnblogs.com/wanghao4023030/p/10732381.html
Copyright © 2011-2022 走看看