Python while循环与for循环

30 阅读5分钟

一、循环之while循环

  1. 循环的语法与基本使用

    while 条件:
         代码1
         代码2
         代码3
    

    while的运行步骤:

    步骤1:如果条件为真,那么依次执行:代码1、代码2、代码3、...... 步骤2:执行完毕后再次判断条件,如果条件为True则再次执行:代码1、代码2、代码3、......,如果条件为False,则循环终止。

    count=0
    while count < 5:
        print(count)  # 0,1,2,3,4
        count+=1
    
  2. 死循环与效率问题

    count = 0
    while count < 5:
        print(count)  # 0......
    
    while True:
        name = input('your name >>>> ')
        print(name)
    
    #纯计算无io的死循环会导致致命的效率问题
    while 1:  # 1就是True
        1+1
    
  3. 循环的应用

    username = 'python'
    password = '123'
    tag = True
    while tag:
        inp_name = input('请输入您的账号:')
        inp_pwd = input('请输入您的密码:')
    
        if inp_name == username and inp_pwd == password:
            print('登录成功')
            tag = False  # 之后的代码还会运行,下次循环判断条件时才生效
        else:
            print('账号名或密码错误')
        print('====end====')
    
  4. 退出循环的两种方式

    a. 条件:将条件变成假

    例如“3.循环的应用”中的示例代码,将条件改为False,等到下次循环判断条件时才会生效。

    b. while + break

    只要运行到break就会立刻终止本层循环。

    username = 'python'
    password = '123'
    
    while True:
        inp_name = input('请输入您的账号:')
        inp_pwd = input('请输入您的密码:')
    
        if inp_name == username and inp_pwd == password:
            print('登录成功')
            break  # 从这里立刻终止本层循环,且循环内这里后面的程序不再被执行,所以也看不到最后的“====end====”。
        else:
            print('账号名或密码错误')
        print('====end====')
    
  5. while循环嵌套

    #通过条件跳出循环
    tag = True
    while tag:
        while tag:
            while tag:
                tag = False
    
    # 通过break跳出循环,每一层都必须配一个break
    while True:
        while True:
            while True:
                break
            break
        break
    

    改变条件的方式:

    username = 'python'
    password = '123'
    
    tag = True
    while tag:
        inp_name = input('请输入您的账号:')
        inp_pwd = input('请输入您的密码:')
    
        if inp_name == username and inp_pwd == password:
            print('登录成功')
            while tag:
                cmd = input("输入命令>: ")
                if cmd == 'q':
                    tag = False
                else:
                    print('命令{x}正在运行'.format(x=cmd))
        else:
            print('账号名或密码错误')
    

    break的方式:

    username = 'python'
    password = '123'
    
    while True:
        inp_name = input('请输入您的账号:')
        inp_pwd = input('请输入您的密码:')
    
        if inp_name == username and inp_pwd == password:
            print('登录成功')
            while True:
                cmd = input("输入命令>: ")
                if cmd == 'q':
                    break
                print('命令{x}正在运行'.format(x=cmd))
            break  # 立刻终止本层循环
        else:
            print('账号名或密码错误')
    
  6. while+continue

    结束本次循环,直接进入下一次。

    强调:在continue之后添加同级代码毫无意义,因为永远无法运行。

    #打印0、1、2、3、5
    count=0
    while count < 6:
        if count == 4:
            count+=1
            continue
            # count+=1  # 错误 
        print(count)
        count+=1
    
  7. while+else

    while True:
        ...
    else:
        print('else包含的代码会在while循环结束后,并且while循环是在没有被break打断的情况下,正常结束的,才会运行。')
    
    count = 0
    while count < 6:
        if count == 4:
            count += 1
            continue
        print(count)
        count += 1
    else:
        print('Python is my friend')
    # 0
    # 1
    # 2
    # 3
    # 5
    # Python is my friend
    
    count=0
    while count < 6:
        if count == 4:
            break
        print(count)
        count += 1
    else:
        print('======>')
    # 0
    # 1
    # 2
    # 3
    

    可以这么说,while + else中的else是针对break的。

二、循环之for循环

理论上,for循环能做的事情,while循环都可以做,之所以要有for循环,是因为for循环在循环取值(遍历取值)上比while循环更简洁。

  1. for循环的语法

    语法:

    for 变量名 in 可迭代对象:  # 可迭代对象可以是:列表、字典、字符串、元组、集合
        代码1
        代码2
        代码3
        ...
    
  2. for循环基本使用

    (1)for基本使用之循环取值

    案例1:列表循环取值
    # 简单版
    l = ['张三', '李四', '王五']
    for x in l:
        print(x)
    
    # 复杂版:
    l = ['张三', '李四', '王五']
    i = 0
    while i < 3:
        print(l[i])
        i += 1
    
    案例2:字典循环取值
    # 简单版
    dic = {'k1': 111, 'k2': 2222, 'k3': 333}
    for k in dic:
        print(k,':',dic[k])
    
    # 复杂版:while循环可以遍历字典,但实在太麻烦了
    
    案例3:字符串循环取值
    # 简单版
    msg = "you can you up,no can no bb"
    for x in msg:
        print(x)
    
    # 复杂版:while循环可以遍历字符串,但实在太麻烦了
    

    (2)for循环与while循环的异同

    a、相同之处:都是循环,for循环可以干的事,while循环也可以干。 b、不同之处: while循环称之为条件循环,循环次数取决于条件何时变为假 for循环称之为"取值循环",循环次数取决in后可迭代对象包含的值的个数

    (3)for循环控制循环次数:range()

    in后直接放一个数据类型来控制循环次数有局限性:当循环次数过多时,数据类型包含值的格式需要伴随着增加。

    range(10)  # 0...9
    # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    range(1,9)  # 1...8
    # [1, 2, 3, 4, 5, 6, 7, 8]
    
    #第三个参数为步长,不写默认为1。
    range(1,9,1)  # 1 2 3 4 5 6 7 8 
    # [1, 2, 3, 4, 5, 6, 7, 8]
    
    range(1,9,2)  # 1 3 5 7 
    # [1, 3, 5, 7]
    

    (4)range补充知识

    # 1、for搭配range,可以按照索引取值,但是麻烦,所以不推荐
    l = ['aaa', 'bbb', 'ccc']  # len(l)
    for i in range(len(l)):
        print(i, l[i])
    
    for x in l:
        print(l)
    
    # 2、range()在python3里得到的是一只"会下蛋的老母鸡",在python2中会根据range中的数据开辟对应大小的空间,但python3进行了优化,只占自身函数大小空间。
    
  3. for循环嵌套

    外层循环循环一次,内层循环需要完整的循环完毕。

    for i in range(2):
        print('外层循环-->', i)
        for j in range(3):
            print('内层-->', j)
          
    # 外层循环--> 0
    # 内层--> 0
    # 内层--> 1
    # 内层--> 2
    # 外层循环--> 1
    # 内层--> 0
    # 内层--> 1
    # 内层--> 2
    
  4. for+break

    同while循环一样,且终止for循环只有break一种方案

  5. for+continue

    for i in range(6):  # 0 1 2 3 4 5
        if i == 4:
            continue  # 终止本次循环,直接去下次从头开始
        print(i)  # 0 1 2 3 5
    
  6. for+else

    同while循环一样