为什么同时运行“ else”和“ if”语句?

时间:2019-01-12 23:24:19

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

在发布此问题时,我已经检查了其他标题相似的链接。所有这些都无法回答我的问题,或者不适用于这部分代码。例如,此处的链接: 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")

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

在以下情况下,您可能想使用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")

答案 2 :(得分:1)

要在一系列语句中仅运行一个if语句,您必须具有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")