1

我下面的代码效果很好,但是,如果我选择“1”,代码将运行 if 语句并打印“成功”,但它也会运行 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)
4

3 回答 3

9

你想要elif构造。

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

否则,不同的if语句彼此断开。我添加了一个空行来强调:

if choice == "1":
    ...

if choice == "2":
    ...
else: # choice != 2
    ...
于 2013-07-03T23:45:42.440 回答
2

您正在寻找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)

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

于 2013-07-03T23:46:05.280 回答
0

除了 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) 
于 2013-07-04T00:01:58.210 回答