Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么';其他';和';如果';正在运行的语句?_Python_Python 3.x_If Statement - Fatal编程技术网

Python 为什么';其他';和';如果';正在运行的语句?

Python 为什么';其他';和';如果';正在运行的语句?,python,python-3.x,if-statement,Python,Python 3.x,If Statement,在发布这个问题时,我已经检查了其他具有类似标题的链接。所有这些要么对我的问题没有答案,要么不适用于这段代码。例如,此处的链接: 说这是因为OP在脚本中使用了echo。在这里,我不使用它,但我仍然得到if和else的结果 while True: selection = input("Type a command or use a page selection") if selection in ('exit','quit'): sys.exit() if s

在发布这个问题时,我已经检查了其他具有类似标题的链接。所有这些要么对我的问题没有答案,要么不适用于这段代码。例如,此处的链接: 说这是因为OP在脚本中使用了
echo
。在这里,我不使用它,但我仍然得到
if
else
的结果

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")
可能您希望在此类情况下使用:

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")

要在一系列if语句中只运行一个if语句,每次放置if时,必须使用elseif语句elif,它与其他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")

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

如果1:
()
elif 2:
b()
elif 3:
c()
其他:
d()

if您指的是哪个
if
(代码中有三个独立的
if
s)?你使用的输入数据是什么,你得到了什么,你期望得到什么?我复制/粘贴到python中,输入2,它只打印“这里的第2页文本”,然后循环回到顶部。看起来很好。@GarrGodfrey,是的,但是如果您键入
1
,它将显示第1页和消息“无效的命令和页码”。是的,它就是这样写的。我想OP是想用elif