如果用户在Python中输入了错误的答案,我如何让程序再次提问



我正在为我的计算机科学课制作一个文本冒险代码。我的代码运行得很好,但当程序询问用户是否想再次播放时,如果他们不输入以";y";或";n〃;则程序自动重新启动。我希望它再次询问这个问题,以便用户可以输入正确的输入。我在代码的那部分附近加了一个#。

school_map = """This is the map of your school.
-------------------------------------------
| classroom A | classroom B | classroom C |
|______ ______|_______ _____|______ ______|
|                                         |
|-------   ---------|                     |
|                   |---------   ---------|
|     cafeteria     |                     |
|                   |                     |
|___________________|         gym         |
|                   |                     |
|   locker rooms                          |
|___________________|_____________________|
|              ☘️             🪨      🍁  |
|      🍄           garden       🌸      |
|  🍀        🥀             🌷           |
-------------------------------------------
"""
def get_choice(prompt) -> int:
while True:
choice = input(prompt).lower()
if choice == "x":
print(school_map)
elif choice in "12":
return int(choice)
else:
print("Value must be 1 or 2.")

while True:
print("WELCOME TO LIVRE DE LA MORT.")
print("*.*.*.*.*.*.*.*.*.*.*.*.*.*.")
print(" ")
name = input("What is your name? ")
print(f"You are a genius high school senior, {name}, whose goal in life is to bring justice to the world.")
print(school_map)
print("If you want to see the map again, input 'X' at any given time.")
print("You are skipping gym class in the locker rooms and looking out a window when you see a notebook fall from the sky.")
if get_choice(
"You can either: 1 - go and pick it up, or 2 - ignore it: "
) == 1:
print("You pick up the notebook and find instructions written on the inside.")
print("WELCOME.")
print("I AM THE LIVRE DE LA MORT.")
print("SINCE YOU HAVE PICKED ME UP, YOU ARE THE CHOSEN ONE.")
print("IF YOU WRITE ANY PERSON'S NAME IN THIS BOOK, AS LONG AS YOU KNOW THEIR FACE, THEY WILL DIE WITHIN THE NEXT 5 MINUTES.")
if get_choice(
"WILL YOU: 1 - JOIN ME IN THIS BATTLE FOR JUSTICE, or 2 - PUT ME BACK DOWN AND HAVE YOUR MEMORY WIPED? "
) == 1:
print("Good. We shall work together.")
break
else:
print("Your memory has been wiped.")
else:
print("You graduate high school and work a 8-6 job for the rest of your life as a police officer. ")
#what if user presses the wrong key?
playagain = input("Would you like to play again? ").lower()
if playagain.startswith("y"):
print("ok.")
print(" ")
print("*.*.*.*.*.*.*.*.*.*.*.*.*.*.")
elif playagain.startswith("n"):
print("You are the weak link. Goodbye.")
exit()

您可以使用更改代码的这一部分

# Rest of the code
# .
# .
# .
playagain = input("Would you like to play again? ")
while playagain:
if playagain.startswith("y"):
print("ok.")
print(" ")
print("*.*.*.*.*.*.*.*.*.*.*.*.*.*.")
break
elif playagain.startswith("n"):
print("You are the weak link. Goodbye.")
exit()
else:
playagain = input("Would you like to play again? ")

相关内容

最新更新