I'm making a text-based adventure game for school, I've made this loop so if you don't give the answers allotted by the program, it will ask you over and over until you give it what it wants. I've made it loop, but I don't know how to exit the loop?
playerchoice =""
while (playerchoice != "wake" or "remain asleep" ):
playerchoice = input("Do you wake, or remain asleep? wake/remain asleep: ")
if playerchoice == "wake":
print ("'Finally! I was starting to think I'd need to call the undertaker. Try not falling asleep in my front yard next time you're feeling tired?'")
elif playerchoice == "remain asleep":
print ("'Are you dead?' they ask again, kicking you in the leg this time. Reluctantly, you sit up. 'Oh, good.'")
else:
print ("Please type a valid answer.")
CodePudding user response:
playerchoice = ""
choices = ["wake", "remain asleep"]
while True:
playerchoice = input("Do you wake, or remain asleep? wake/remain asleep: ")
if playerchoice == "exit":
break
if playerchoice == "wake":
print("'Finally! I was starting to think I'd need to call the undertaker. Try not falling asleep in my front yard next time you're feeling tired?'")
elif playerchoice == "remain asleep":
print(
"'Are you dead?' they ask again, kicking you in the leg this time. Reluctantly, you sit up. 'Oh, good.'")
elif (choices.__contains__(playerchoice)) == False:
print("Please type a valid answer.")
You can use the break statement to break the loop, but a better approach would be to use something like a 'switch statement' in python.
CodePudding user response:
Another way is the following
choices = {
"wake": "'Finally! I was starting to think I'd need to call the undertaker. Try not falling asleep in my front yard next time you're feeling tired?'",
"remain asleep": "'Are you dead?' they ask again, kicking you in the leg this time. Reluctantly, you sit up. 'Oh, good.'"
}
playerchoice = ""
while (playerchoice not in choices):
playerchoice = input(
"Do you wake, or remain asleep? wake/remain asleep: ")
try:
print(choices[playerchoice])
except KeyError:
print("Please type a valid answer.")
possible choices are in a dictionary,
you simply check your loop for not valid answers.
CodePudding user response:
you should use break
to exit loop when desired input is given.
playerchoice =""
while True:
playerchoice = input("Do you wake, or remain asleep? wake/remain asleep: ")
if playerchoice == "wake":
print ("'Finally! I was starting to think I'd need to call the undertaker. Try not falling asleep in my front yard next time you're feeling tired?'")
break
elif playerchoice == "remain asleep":
print ("'Are you dead?' they ask again, kicking you in the leg this time. Reluctantly, you sit up. 'Oh, good.'")
break
else:
print ("Please type a valid answer.")