首页 > 其他分享 >循环语句:while

循环语句:while

时间:2022-09-01 11:26:21浏览次数:73  
标签:语句 count 示例 while 循环 print 运行

循环语句:while

1. while语句结构:while+条件

  • 示例1:

    while True:
        print("人生苦短,我用Python。")
    

    运行得到的结果是循环打印“人生苦短,我用python。”
    image

  • 示例2:

    while 1>0 and 2>1:
        print("人生苦短,我用Python。")
    

    运行得到的结果也是循环打印“人生苦短,我用python。”

  • 示例3
    通过循环,让count每次都+1

    count = 1
    while True:
        print(count)
        count = count + 1
    

    运行得到的结果是,从1开始每次循环+1
    image

  • 示例4
    通过循环,打印从1到10

    count = 1
    while count <= 10:
        print(count)
        count = count + 1
    print("结束")
    

    运行结果
    image

  • 示例5
    通过循环,打印从1、2、3、4、5、6、8、9、10

    # 我的方法
    count = 1
    while count <= 10:
        print(count)
        count = count + 1
        if count == 7:
            count = count +1
    print("结束")
    

    运行结果
    image

    其他方法同样可以实现:

    # 其他同学的方法
    count = 1
    while count <= 6:
        print(count)
        count = count + 1
    count = 8
    while count <= 10:
        print(count)
        count = count + 1
        
    # 老师的方法1
    count = 1
    while count <= 10:
        if count != 7:
            print(count)
        count = count + 1
    print("结束")
    
    # 老师的方法2
    count = 1
    while count <= 10:
        if count == 7:
            pass
        else:
            print(count)
        count = count + 1
    print("结束")
    

2. 关键字:break

break,跳出当前循环

  • 示例1

    count = 1
    while count <= 10:
        if count == 7:
            break
        print(count)
        count = count + 1
    print("结束")
    

    运行结果
    image

  • 示例2:通过break实现,打印1~10

    count = 1
    while True:
        print(count)
        if count == 10:
            break
        count = count + 1
    print("结束")
    

    运行结果
    image

3. 关键字:continue

continue,本次循环如果遇到continue,则不再继续向下运行,回到while条件位置

  • 示例:使用continue,打印1,2,3,4,5,6,8,9,10

    # 方法1
    count = 1
    while count <= 10:
        if count == 7:
            count += 1  # count += 1 ; 等效于:count = count + 1 ;
            continue
        print(count)
        count += 1
    print("结束")
    
    # 方法2
    count = 1
    while count <= 10:
        print(count)
        if count == 6:
            count += 2  
            continue
        count += 1
    print("结束")
    

    运行结果
    image

4. while else

用的比较少:else在不满足while条件,或者条件为false时触发

  • 示例1

    count = 1
    while count <= 10:
        print(count)
        count = count + 1
    else:
        print("正常完成")
    print("结束")
    

    运行结果
    image

  • 示例2

    count = 1
    while count <= 10:
        print(count)
        if count == 7:
            break
        count = count + 1
    else:
        print("正常完成")
    print("结束")
    

    运行结果
    image

    因为count=7时,执行了break,跳出循环,而非while的条件不满足,因此else未执行

标签:语句,count,示例,while,循环,print,运行
From: https://www.cnblogs.com/timo521/p/Python_while01.html

相关文章