【问题标题】:Loops in Python 3 [duplicate]Python 3中的循环[重复]
【发布时间】:2014-05-04 14:08:04
【问题描述】:

我如何获得它,以便我可以使用“或”来制作一个 while 循环

    start = input(("Would you like to start? "))
    while start == "yes" or "YES" or "Yes":

然后我有代码

    start = input(("Would you like to start again? "))
    if start == "no" or "No" or "NO":
       break

当我尝试此代码时,它不起作用。无论我输入什么,它都会从开头开始代码并在结尾处中断。有人可以帮忙吗?

【问题讨论】:

    标签: python loops python-3.x while-loop


    【解决方案1】:

    由于or 的优先级高于==

    start == "yes" or "YES" or "Yes":
    

    将被评估为

    (start == "yes") or ("YES") or ("Yes")
    

    你可以这样做

    while start.lower() == "yes":
    

    同理,

    if start.lower() == "no":
    

    【讨论】:

    • start.lower() in ('y', 'yes')
    【解决方案2】:

    or 之间的每个语句都是分开的。所以你实际上检查是否 start == "yes"True"YES"True 等等。
    由于"YES" 不是一个空字符串,它被认为是True 布尔值。

    我想把它改成这样的:

    while (start == "yes") or (start == "YES") or (start == "Yes"):
    

    甚至:

    while start.lower() == "yes":
    

    【讨论】:

      【解决方案3】:

      而不是这个:

      while start == "yes" or "YES" or "Yes":
      

      这样做(与 if 相同):

      while start == "yes" or start== "YES" or start == "Yes":
      

      或者,更好的是,这样做:

      while start.lower() == "yes":
      

      你也可以这样做:

      while start.lower().startswith('y'):
      

      所以如果用户输入任何以 'y' 开头的内容,它将执行 while 语句中的任何内容。

      【讨论】:

        猜你喜欢
        • 2018-03-04
        • 2021-10-17
        • 2016-10-02
        • 2020-10-18
        • 1970-01-01
        • 2022-12-16
        • 1970-01-01
        • 2016-10-04
        • 2014-12-07
        相关资源
        最近更新 更多