zoukankan      html  css  js  c++  java
  • while循环

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

    '''
    print(1)
    while 条件:
         代码1
         代码2
         代码3
    print(3)
    '''
    
    count=0
    while count < 5: # 5 < 5
        print(count) # 0,1,2,3,4
        count+=1 # 5
    
    print('顶级代码----->')
    
    0
    1
    2
    3
    4
    顶级代码----->
    

    2.死循环与效率

    # while True:
    #     name=input('your name >>>> ')
    #     print(name)
    
    # 纯计算无io的死讯会导致致命的效率问题
    # while True:
    #     1+1
    

    3.退出循环的方式

    3.1 将条件改为False,等到下次循环判断条件时才会生效

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

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

    while True:
        inp_name=input('请输入您的账号:')
        inp_pwd=input('请输入您的密码:')
    
        if inp_name  == username and inp_pwd == password:
            print('登录成功')
            break # 立刻终止本层循环
        else:
            print('账号名或密码错误')
    
        # print('====end====')
    

    4. while循环嵌套与结束

    '''
    tag=True
    while tag:
        while tag:
            while tag:
                tag=False
        
    
    # 每一层都必须配一个break
    while True:
        while True:
            while True:
                break
            break
        break
    '''
    

    5. while +continue:结束本次循环,直接进入下一次,在continue之后添加同级代码毫无意义,因为永远无法运行

    count=0
    while count < 6:
        if count == 4:
            count+=1
            continue
            # count+=1 # 错误
        print(count)
        count+=1
        
    0
    1
    2
    3
    5
        
    

    6. while+else:针对break

    count=0
    while count < 6:
        if count == 4:
            count+=1
            continue
        print(count)
        count+=1
    else:
        print('else包含的代码会在while循环结束后,并且while循环是在没有被break打断的情况下正常结束的,才不会运行')
        count=0
    while count < 6:
        if count == 4:
            break
        print(count)
        count+=1
    else:
        print('======>')
        
        
    1
    2
    3
    5
    else包含的代码会在while循环结束后,并且while循环是在没有被break打断的情况下正常结束的,才不会运行
    0
    1
    2
    3    
    
  • 相关阅读:
    快速排序
    ABP Error in roboto.css can't resolve '97uahxiqZRoncBaCEI3aWxJtnKITppOI_IvcXXDNrsc.woff2'
    .NET Core Log
    .NET Core的配置文件
    VirtualBox多网卡模式
    Maven 常见错误
    python压缩文件脚本
    Windows7 64bit 安装python3.3 & cx_Freeze-4.3.2
    Ubuntu Linux环境变量
    Ubuntu12.04 64bit 安装 Dropbox
  • 原文地址:https://www.cnblogs.com/chenyoupan/p/12449374.html
Copyright © 2011-2022 走看看