zoukankan      html  css  js  c++  java
  • 024 流程控制之for循环

    一、语法

    为什么有了while循环,还需要有for循环呢?不都是循环吗?我给大家出个问题,我给出一个列表,我们把这个列表里面的所有名字取出来。

    name_list = ['xucheng', 'xc', 'xyc', 'sean']
    
    n = 0
    while n < 4:
        # while n < len(name_list):
        print(name_list[n])
        n += 1
    

    ​ 输出内容:

    ​ xucheng

    ​ xc

    ​ xyc

    ​ sean

    字典也有取多个值的需求,字典可能有while循环无法使用了,这个时候可以使用我们的for循环。

    info = {'name': 'xucheng', 'age': 19}
    
    for item in info:
        # 取出info的keys
        print(item)
    

    ​ 输出内容:

    ​ name

    ​ age

    name_list = ['xucheng', 'xc', 'xyc', 'sean']
    for item in name_list:
        print(item)
    

    ​ 输出内容:

    ​ xucheng

    ​ xc

    ​ xyc

    ​ sean

    二、for + break

    for循环调出本层循环。

    # for+break
    name_list = ['xucheng', 'xc', 'xyc', 'sean']
    for name in name_list:
        if name == 'xyc':
            break
        print(name)
    

    ​ 输出内容:

    ​ xucheng

    ​ xc

    三、for + continue

    for循环调出本次循环,进入下一次循环

    # for+continue
    name_list = ['xucheng', 'xc', 'xyc', 'sean']
    for name in name_list:
        if name == 'xyc':
            continue
        print(name)
    

    ​ 输出内容:

    ​ xucheng

    ​ xc

    ​ sean

    四、for循环嵌套

    外层循环循环一次,内层循环循环所有的。

    # for循环嵌套
    for i in range(3):
        print(f'-----:{i}')
        for j in range(2):
            print(f'*****:{j}')
    

    五、for + else

    for循环没有break的时候触发else内部代码块。

    # for+else
    name_list = ['xucheng', 'xc', 'xyc', 'sean']
    for name in name_list:
        print(name)
    else:
        print('for循环没有被break中断掉')
    

    ​ 输出信息:

    ​ nick
    ​ jason
    ​ tank
    ​ sean
    ​ for循环没有break中断掉

    六、for循环实现loading

    import time
    
    print('Loading', end='')
    for i in range(6):
        print(".", end='')
        time.sleep(0.2)
    

    ​ 输出信息:

    ​ Loading......

  • 相关阅读:
    VS使用技巧
    写的一个简单定时器(非独立线程)
    C/C++技巧
    【转载】R6034错误,C Runtime Error
    C/C++面试题(一)
    常用的coco2d-x游戏开发工具(转)
    AndroidJNI 调用JAVA(转)
    Android SDK +Eclipse+ADT+CDT+NDK 开发环境在windows 7下的搭建
    简单的字符串压缩--C代码
    SQLite: sqlite_master(转)
  • 原文地址:https://www.cnblogs.com/XuChengNotes/p/11284852.html
Copyright © 2011-2022 走看看