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

    for 循环用于针对集合中的每个元素都一个代码块,而while 循环不断地运行,直到指定的条件不满足为止。

    7.2.1 使用while 循环

    7.2.2 让用户选择何时退出

    7.2.3 使用标志

    在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志

    可让程序在标志 为True 时继续运行,并在任何事件导致标志的值为False 时让程序停止运行

    在while 语句中就只需检查一个条件——标志的当前值是否为True ,并将所有测试(是 否发生了应将标志设置为False 的事件)都放在其他地方,从而让程序变得更为整洁,标志命名为(可给它指定任何名称)

    7.2.4 使用break 退出循环

    ,可使用break 语句来退出遍历列表或字典的for 循环

    prompt = "
    Tell me something, and I will repeat it back to you:"
    prompt += "
    Enter 'quit' to end the program. "
    
    while True: #以while True 打头的循环将不断运行,直到遇到break 语句
        city=input(prompt)
        if city=='quit':
            break
        else:
            print("I'd love to go to " + city.title() + "!")
            

    结果

    Tell me something, and I will repeat it back to you:
    Enter 'quit' to end the program. sarch
    I'd love to go to Sarch!
    
    Tell me something, and I will repeat it back to you:
    Enter 'quit' to end the program. quit
    >>> 

    7.2.5 在循环中使用continue

    current_number = 0
    while current_number < 10:
        current_number += 1   #们以步长1的方式往上数
        if current_number % 2 == 0: #求模运算为0,继续返回while
            continue
        print(current_number)     
    1
    3
    5
    7
    9
    >>> 

    当我们输入信息时,程序运行;当我们输入退出条件的时候,程序是不执行continue后面的语句了,但是程序继续运行,从新询问我们,并没有停止运行,

    7.2.6 避免无限循环

     如果程序陷入无限循环,可按Ctrl+ C,也可关闭显示程序输出的终端窗口。

  • 相关阅读:
    SQL Server 阻止了对组件 'Ole Automation Procedures' 的 过程'sys.sp_OACreate' 的访问
    谷歌浏览器扩展程序manifest.json参数详解
    获取天气api
    UVA 10385 Duathlon
    UVA 10668 Expanding Rods
    UVALIVE 3891 The Teacher's Side of Math
    UVA 11149 Power of Matrix
    UVA 10655 Contemplation! Algebra
    UVA 11210 Chinese Mahjong
    UVA 11384 Help is needed for Dexter
  • 原文地址:https://www.cnblogs.com/jdy113/p/8012250.html
Copyright © 2011-2022 走看看