If-else语句如何跳过else?

2024-09-19 23:32:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我下面的代码工作得很好,但是,如果我选择“1”,代码将运行if语句并打印“success”,但它也将运行else语句并退出。如果用户选择1、2或3,如何停止else语句的运行?在

谢谢!在

print "\nWelcome to the tool suite.\nWhich tool would you like to use?\n"
print "SPIES - press 1"
print "SPADE - press 2"
print "SPKF - press 3"
print "For information on tools - press i\n"

choice = raw_input("")
if choice == "1":
    execfile("lot.py")
    print ("success")

if choice == "2":
    #execfile("spade.py")
    print ("success")

if choice == "3":
    #execfile("spkf.py")
    print ("success")

if choice == "i":
    print "Google Maps is awesome.\n"
    print "SPADE\n"
    print "SPKF\n\n"

else:
    print "Error, exiting to terminal"
    exit(1)

Tags: to代码用户pyif语句toolelse
3条回答

您也可以使用映射来完成此操作,而不是使用长链if、elif和else:

def one():
    print "success one"

def two():
    print "success two"  

def three():
    print "success three"

def inf():
    print "Google Maps is awesome."
    print "SPADE"
    print "SPKF\n"    

choices={
    '1':one,
    '2':two,
    '3':three,
    'i':inf
}

try:
    choices[raw_input("Enter choice: ").lower()]()
except KeyError:
    print "Error, exiting to terminal"
    exit(1) 

您正在寻找elif

if choice == "1":
    execfile("lot.py")
    print ("success")

elif choice == "2":
    #execfile("spade.py")
    print ("success")

elif choice == "3":
    #execfile("spkf.py")
    print ("success")

elif choice == "i":
    print "Google Maps is awesome.\n"
    print "SPADE\n"
    print "SPKF\n\n"

else:
    print "Error, exiting to terminal"
    exit(1)

这使得整个块位于单个条件构造之上

您需要elif构造。在

if choice == "1":
    ...
elif choice == "2":
    ...
else: # choice != "1" and choice != "2"
    ...

否则,不同的if语句将彼此断开连接。我添加了一个空白行作为强调:

^{2}$

相关问题 更多 >