Python 如何用“是”或“否”问题限制用户输入
我正在制作一个游戏,它要求用户回答一个问题。这个问题是肯定还是否定的:Python 如何用“是”或“否”问题限制用户输入,python,Python,我正在制作一个游戏,它要求用户回答一个问题。这个问题是肯定还是否定的: 我有这个,但我需要这样做,以便用户只能输入是或否。在循环时使用。当他们键入有效响应时中断循环,否则重复 print("Lying on the ground next to you is a stone slab.") while True: pick = input("Do you pick up the slab? Yes/No ").lower() if pick
我有这个,但我需要这样做,以便用户只能输入是或否。在循环时使用
。当他们键入有效响应时中断循环,否则重复
print("Lying on the ground next to you is a stone slab.")
while True:
pick = input("Do you pick up the slab? Yes/No ").lower()
if pick == 'yes':
print("You pick up the slab and begin reading.")
break
elif pick == 'no':
print("You walk forwards and land facefirst onto the slab.")
break
else:
print("You have to choose Yes or No")
您可以将输入转换为单个案例,这样就不必重复yes
和yes
的测试,您可以通过这种方式来完成
print("Lying on the ground next to you is a stone slab.")
pick = input("Do you pick up the slab? Yes/No ")
print(" ")
if pick=="yes":
print("You pick up the slab and begin reading.")
elif pick=="no":
print("Lying on the ground next to you is a stone slab.")
else:
print("Answer Must Be 'Yes' or 'No'")
您可以使用to循环,直到得到“是”或“否”
while True:
try:
pick = input("Do you pick up the slab? Yes/No ").lower()
print(" ")
if pick != "yes" && pick != "no":
raise IncorrectInput()
else:
#something
break
except IncorrectInput():
print("please input yes or no")
使用while
循环检查输入是否符合规则,否则要求用户重新输入
print("Lying on the ground next to you is a stone slab.")
while True:
pick = input("Do you pick up the slab? Yes/No \n> ")
pick = pick.lower().strip()
if pick == "yes" or pick == "y" :
print("You pick up the slab and begin reading.")
break
elif pick =="no" or pick == "n":
print("You walk forwards and fall facefirst onto the slab.")
break
else:
print("Please input Yes/No.")
如果要提示用户直到输入有效,可以使用循环:
print("Lying on the ground next to you is a stone slab.")
while True:
pick = input("Do you pick up the slab? Yes/No ").lower() # This will make the user input not case-senitive
try:
if pick == "yes":
print("You pick up the slab and begin reading.")
elif pick == "no":
print("Lying on the ground next to you is a stone slab.")
else:
raise Exception("Invalid input! Answer Must Be 'Yes' or 'No'")
except Exception as e:
print(e)
else:
break
print("Lying on the ground next to you is a stone slab.")
while True:
pick = input("Do you pick up the slab? Yes/No ").lower() # This will make the user input not case-senitive
try:
if pick == "yes":
print("You pick up the slab and begin reading.")
elif pick == "no":
print("Lying on the ground next to you is a stone slab.")
else:
raise Exception("Invalid input! Answer Must Be 'Yes' or 'No'")
except Exception as e:
print(e)
else:
break