【问题标题】:Why are both the 'else' and 'if' statements running? [duplicate]为什么“else”和“if”语句都在运行? [复制]
【发布时间】:2019-01-12 23:24:18
【问题描述】:

在发布此问题时,我已经检查了具有相似标题的其他链接。所有这些要么对我的问题没有答案,要么不适用于这段代码。例如,这里的链接: Why is my batch script running both if and else statement when if statement matches? 说这是因为 OP 在脚本中使用了echo。在这里,我不使用它,但我仍然得到ifelse 的结果。

while True:
    selection = input("Type a command or use a page selection")
    if selection in ('exit','quit'):
        sys.exit()
    if selection in ('page 1','1'):
        print("Page 1 text here")
    if selection in ('page 2','2'):
        print("Page 2 text here")
    else:
        print("Invalid command or page number")

【问题讨论】:

  • 您指的是哪个if(您的代码中有三个单独的ifs)?你使用什么输入数据,你得到什么,你期望什么?
  • 我复制/粘贴到python中,输入2,它只打印“第2页文本”,然后循环回到顶部。似乎工作正常。
  • @GarrGodfrey,是的,但是如果你输入 1,它会给你第 1 页和消息“无效的命令和页码”。
  • 没错,就是这么写的。我想 OP 打算使用 elif

标签: python python-3.x if-statement


【解决方案1】:

如果这是一个长条件 - 你必须在中间使用 elif:

if 1:
    a()
elif 2:
    b()
elif 3:
    c()
else:
    d()

【讨论】:

    【解决方案2】:

    可能你想在这些情况下使用if-elif-else

    while True:
        selection = input("Type a command or use a page selection")
        if selection in ('exit','quit'):
            sys.exit()
        elif selection in ('page 1','1'):
            print("Page 1 text here")
        elif selection in ('page 2','2'):
            print("Page 2 text here")
        else:
            print("Invalid command or page number")
    

    【讨论】:

      【解决方案3】:

      要在一系列的 if 语句中只运行一个 if 语句,你必须有 else if 语句,elif,所有你放 if 的语句,它与其他 if/elif/else 语句一起被考虑。你的 else 语句独立于前两个 if 语句,我在下面修复了它。

      while True:
          selection = input("Type a command or use a page selection: ")
          if selection in ('exit','quit'):
              sys.exit()
          elif selection in ('page 1','1'):
              print("Page 1 text here")
          elif selection in ('page 2','2'):
              print("Page 2 text here")
          else:
              print("Invalid command or page number")
      

      【讨论】:

        猜你喜欢
        • 2014-06-20
        • 2022-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多