我是一个完全的新手,正在尝试制作数字魔术。我希望程序在用户键入“否”时停止。这是我下面的代码!
print("Hello and welcome to the number magic trick!!")
x = input("Yes or No")
if x == "Yes":
print("Yay!!")
print("Pick an integer number from 1 to 10 but don't tell me!")
print("Multiply this number with 2")
print("Multiply the new number by 5")
print("Now, divide your current number with your original number")
print("Subtract 7 from your current number")
print("Is the answer 3 ?")
elif x == "No":
print("Boo!!")
else:
print("Invalid Input")
y = input ("Yes or No")
if y == "Yes":
print("Cool isn't it?")
elif y == "No":
print("You can't do math!")
else:
print("Invalid input")
答案 0 :(得分:2)
您不必引发错误,只需使用exit
方法即可。
if x.strip().lower() == "no":
print("You said no!")
exit(0)
您甚至可以使用exit
模块中的sys
方法,如下所示:
import sys
if x.strip().lower() == "no":
print("You said no!")
sys.exit(0)
信息:0
方法中的exit
表示“该程序已完成,没有任何错误” ,但替换了{{1 }}与0
一起表示“程序出了点问题” ,并且退出并出现错误。
祝你好运。
答案 1 :(得分:1)
您可以引发异常。另外,优良作法是将单行if / else语句放在同一行上。例如,
print("Hello and welcome to the number magic trick!!")
x = input("Yes or No")
if x == "Yes":
print("Yay!!")
print("Pick an integer number from 1 to 10 but don't tell me!")
print("Multiply this number with 2")
print("Multiply the new number by 5")
print("Now, divide your current number with your original number")
print("Subtract 7 from your current number")
print("Is the answer 3 ?")
elif x == "No":
print("Boo!!")
raise SystemExit()
else:
print("Invalid Input")
raise SystemExit()
y = input ("Yes or No")
if y == "Yes":
print("Cool isn't it?")
elif y == "No":
print("You can't do math!")
raise SystemExit()
else:
print("Invalid input")
raise SystemExit()
欢迎您使用此代码...
答案 2 :(得分:1)
if x == "No":
quit()
from sys import exit
if x == "No":
exit()