我最近刚刚完成了一些非常基本的故障排除系统的代码。我只是想添加一些验证,以便如果用户在任何问题上输入任何不是或否的内容,那么它将在shell中打印“无效输入”,但不确定如何完全执行此操作。有谁可以帮助我吗?非常感谢。
我的代码:
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")
答案 0 :(得分:1)
这是你可能采取的一种方式。
定义一个从用户获得“是”或“否”的函数。人们倾向于想要重复这个问题,直到用户给你一个合适的答案:这就是这个功能所做的。
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"):
...