如何在python中打印错误?
我最近刚刚完成了一个非常基本的故障排除系统的一些代码。我只是想添加一些验证,这样,如果用户在任何问题上输入了不是“是”或“否”的内容,那么它将在shell中打印“无效输入”,但不确定如何准确地执行。有人能帮我吗?非常感谢 我的代码:如何在python中打印错误?,python,Python,我最近刚刚完成了一个非常基本的故障排除系统的一些代码。我只是想添加一些验证,这样,如果用户在任何问题上输入了不是“是”或“否”的内容,那么它将在shell中打印“无效输入”,但不确定如何准确地执行。有人能帮我吗?非常感谢 我的代码: prompt = "> " print ("screen question one here") screen = input(prompt) if screen == "yes": print ("screen question two here"
prompt = "> "
print ("screen question one here")
screen = input(prompt)
if screen == "yes":
print ("screen question two here")
screen2 = input(prompt)
if screen2 == "yes":
print ("screen question three here")
screen3 = input(prompt)
if screen3 == "yes":
print ("screen advice one here")
elif screen3 == "no":
print ("screen adivce two here")
elif screen2 == "no":
print ("camera question one here")
camera = input(prompt)
if camera == "yes":
print ("camera question two here")
camera2 = input(prompt)
if camera2 == "yes":
print ("camera advice one here")
elif camera2 == "no":
print ("camera advice two here")
elif camera == "no":
print ("water question one here")
water = input(prompt)
if water == "yes":
print ("water question two here")
water2 = input(prompt)
if water2 == "yes":
print ("water advice one here")
elif water2 == "no":
print ("water advice two here")
elif water == "no":
print ("buttons question one here")
buttons = input(prompt)
if buttons == "yes":
print ("buttons advice one here")
elif buttons == "no":
print ("buttons advice two here")
elif screen == "no":
print ("battery question one here")
battery = input(prompt)
if battery == "yes":
print ("battery question two here")
battery2 = input(prompt)
if battery2 == "yes":
print ("battery advice one here")
elif battery2 == "no":
print ("battery advice two here")
elif battery == "no":
print ("wifi question one here")
wifi = input(prompt)
if wifi == "yes":
print ("wifi advice one here")
elif wifi == "no":
print ("wifi advice two here")
这里有一种方法,你可以这样做 定义一个函数,从用户处获取是或否。人们倾向于重复这个问题,直到用户给你一个合适的回答:这就是这个函数的作用
def yesorno(question):
while True:
print(question)
answer = input('> ').strip().lower()
if answer in ('y', 'yes'):
return True
if answer in ('n', 'no'):
return False
print("Invalid input")
另一方面,如果您只想在获得无效输入时退出脚本,可以执行以下操作:
def yesorno(question):
print(question)
answer = input('> ').strip().lower()
if answer in ('y', 'yes'):
return True
if answer in ('n', 'no'):
return False
exit('Invalid input')
exit
将直接退出整个程序。这不一定是我推荐的
无论哪种方式,您都可以这样使用yesorno
:
if yesorno("Question 1"):
# User answered yes
if yesorno("Question 2A"):
# User answered yes
else:
# User answered no
else:
# User answered no
if yesorno("Question 2B"):
...
首先,编写一个函数,从用户那里得到是或否。集中精力让它按你想要的方式工作,然后你就可以用它来回答所有不同的问题了!但我想你早就知道了。还在挣扎,它要么解决了一些问题,要么根本没有。你能帮忙吗@克尔伍德:这工作非常好!请问.strip()在这段代码中的作用是什么?多谢各位@khelwood从字符串中删除周围的空格,因此如果用户键入
“yes”
,它将转换为“yes”
。