Python-标志

标志

  • 在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于 活动状态。这个变量被称为标志,充当了程序的交通信号灯。你可让程序在标志为 True 时继续运 行,并在任何事件导致标志的值为 False 时让程序停止运行。这样,在 while 语句中就只需检查一 个条件——标志的当前值是否为 True ,并将所有测试(是否发生了应将标志设置为 False 的事件) 都放在其他地方,从而让程序变得更为整洁
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
    message = input(prompt)
    if message != 'quit':
        print(message)
复制代码

使用标志符:

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)
复制代码
  • 使用break
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
    city = input(prompt)
    if city == 'quit':
        break
    else:
        print(("I'd love to go to " + city.title() + "!")
    
复制代码
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务