gpt4 book ai didi

python - If else 语句 - 如何跳过 else?

转载 作者:太空宇宙 更新时间:2023-11-04 06:56:15 26 4
gpt4 key购买 nike

我下面的代码运行良好,但是,如果我选择“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)

最佳答案

您需要 elif 结构。

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

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

if choice == "1":
...

if choice == "2":
...
else: # choice != 2
...

关于python - If else 语句 - 如何跳过 else?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17459857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com