How do I exit a loop in Python? [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
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.")

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.")

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.

Related

Getting out of a while loop using input

i am preparing a function to user to guess a random number generated by computer.
The output should be the number of guesses, and if the guess is correct, lower or higher than the generated number.
In the end the, the user should be asked if he wants to play again or not.
Everything is working excepts this last part, because i can't break the loop to stop the game.
Here's my code:
#random number guessing game
import random
def generate_random (min,max):
return random.randint (min,max)
#generate_random (1,100)
star_range=1
end_range=100
#targetnumber=generate_random(start_range,end_range)
#print (targetnumber)
def main():
targetnumber=generate_random(star_range,end_range)
number_of_guesses =0 #guarda o numero de tentativas do jogador
print ("Guess a number between 0 e 100.\n")
while True:
number_of_guesses +=1
guess = int(input("Guess #" + str(number_of_guesses) + ": "))
if guess > targetnumber:
print("\t Too High, try again.")
elif guess < targetnumber:
print ("\t Too low, try aain")
else:
print ("\t Correct")
print ("\t Congratulations. you got it in",number_of_guesses,"guesses.")
break
playagain=input("\n whould you like to play again? (y/n): ").lower()
while playagain != "y" or playagain != "n":
print ("Please print y to continue or n to exit")
playagain=input("\n whould you like to play again? (y/n): ").lower()
if playagain == "y":
continue
else:
break
My final output is always this one:
whould you like to play again? (y/n): n
Please print y to continue or n to exit
whould you like to play again? (y/n):
Can you please help me, letting me know what i am doing wrong?
Thank you very much
The condition evaluation is always True, hence you get into the loop again.
while playagain not in ['y', 'n']:
...
would satisfy your input check
Also, your continue/break condition is only evaluated if the while loop condition is met (i.e., the input was not correct)
It looks like you are continuing the second "while" loop and not moving back to your "game" code when you check the equality of the string "y" as the input, thus the question gets asked again. Instead, you should try refactoring the loops so that your game loop is nested inside the retry loop.

How to make python code go back to the original question after it hits the else or elif in an if else statement instead of quitting the code

For example:
if answer == "1":
print ("right answer")
elif answer == "2":
print ("Wrong answer. Try again")
else:
print ("Invalid input: Please try again")
So that was just a quick example of what I'm trying to say. Instead of allowing the user to enter the answer again, the code quits and they have to go through the whole thing.
How can I make it so that they get to return to the original answer instead of starting the entire code over again?
Thank you.
EDIT: I should have used the actual code instead of an example because I can't understand it in the context of my actual code.
print ("\nYou do not have any dogs treats. Maybe you should have grabbed some--your mother always keeps the dog treats in one of the bedrooms upstairs.")
next_choice = input("\nWhat do you do now?\n1. Go back upstairs and get the dog treats\n2. Walk down anyway\n")
if next_choice == "1":
which_bedroom = input ("\nYou go back upstairs to look for the dog treats. Which room do you go to first?\n1. Your bedroom\n2. Your sister's bedroom\n3. The bathroom\n4. Your mother's bedroom\n")
if which_bedroom == "1":
print ("This is where you first started. There is nothing here. Please try again.")
elif which_bedroom == "2":
print ("There is nothing here. Please try again.")
elif which_bedroom == "3":
print ("The bathroom is locked--your sister must be in there. Why would there be dog treats in the bathroom anyway? Please try again.")
elif which_bedroom == "4":
print ("Congrats! You found the dog treats along with a note that says: 1970")
downstairs_again = input ("You go back downstairs, and yet again, your dogs spots you. What do you do?\n1. Walk down anyway\n2. Give him the dog treats\n")
Depending on the specific application your code block and if conditions might be different, but from your example it would be something akin to this.
answered=False
while(not answered):
if answer=='1':
answered=True
print('Right answer')
elif answer=='2':
print('Wrong answer try again')
else:
print('Invalid input try again')
EDIT:
I'm assuming your function input() is handling all UI inputs behind the scenes.
answered=False
while(not answered):
which_bedroom = input('....') #insert your long string
if which_bedroom=='1':
print('wrong answer try again')
elif which_bedroom =='2':
print('wrong answer try again')
elif which_bedroom == '3':
answered=True
print('correct! next question...')
else:
print('Invalid input try again')
next_question() #copy above for downstairs_again instead of nesting it in this loop
Since you created a new variable for your second question after your first question is correctly answered, I assume you have completely different if-else conditions for your next question. I'd therefore recommend implementing a similar while loop for the new question if your text-dungeon-crawler-esque adventure is relatively short and you're just trying to get a proof of concept.
Put it in a while loop:
while (answer := input("QUESTION: ") != "1":
print("Wrong answer. Try again" if answer == "2" else "Invalid input: Please try again")
Without the fancy stuff:
answer = None
while answer != "1":
answer = input("QUESTION: ")
if answer == "2":
print ("Wrong answer. Try again")
else:
print ("Invalid input: Please try again")
EDIT: Here's what your code will look like using the above:
print ("\nYou do not have any dogs treats. Maybe you should have grabbed some--your mother always keeps the dog treats in one of the bedrooms upstairs.")
while (next_choice := input("\nWhat do you do now?\n1. Go back upstairs and get the dog treats\n2. Walk down anyway\n")) != "1":
if next_choice == "2":
print("whatever you want to print after picking 2")
print("whatever you want to print after picking 1")
while (which_bedroom := input ("\nYou go back upstairs to look for the dog treats. Which room do you go to first?\n1. Your bedroom\n2. Your sister's bedroom\n3. The bathroom\n4. Your mother's bedroom\n")) != "4":
if which_bedroom == "1":
print ("This is where you first started. There is nothing here. Please try again.")
elif which_bedroom == "2":
print ("There is nothing here. Please try again.")
elif which_bedroom == "3":
print ("The bathroom is locked--your sister must be in there. Why would there be dog treats in the bathroom anyway? Please try again.")
print ("Congrats! You found the dog treats along with a note that says: 1970")
while (downstairs_again := input ("You go back downstairs, and yet again, your dogs spots you. What do you do?\n1. Walk down anyway\n2. Give him the dog treats\n")) != "correct choice":
pass #do stuff
while loops are an easy way to accomplish this, but look into using classes holding objects of the same class to easily build and execute a tree of choices.

Im unable to stop the input from taking place & play again loop middle of script

I am making a custom version of hangman for a college assignment using python, but currently I'm having an issue with two parts to my code, its a game of hangman.
I have included the entire code below so that if anyone can answer they have the full information from the code.
The issues I'm having are that this part of the code is not ignoring the input before so it still lets you guess multiple letters.
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
The second issue I have is that once you win the game it doesn't ask if you want to play again properly (I have tried multiple methods to try to fix this including another while loop inside the if statement.
if failed == 0:
print("Ye be living for now")
print("The word was: " + myword)
print
...
while True:
...
if failed == 0:
print("Ye be living for now")
print("The word was: " + myword)
# Current Bug: Play again here, cannot use same line as end.
print
guess = input("guess a letter: ").lower()
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
# Current Bug: still takes input into consideration when it shouldn't
guesses += guess
...
play_again = input("If you'd like to play again, please type 'yes' or 'y': ").lower()
if play_again == "yes" or play_again == "y":
continue
else:
play_again != "yes" or play_again != "y"
break
This should solve your problem of taking multiple letters as input
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
# Current Bug: still takes input into consideration when it shouldn't
else:
guesses += guess
This will only add the input to guesses if its length is less than 1.
And if you want to ask the game to play again, after winning put your code in a while loop. Something like this:
play_again = 'y'
while(play_again == 'y' or play_again='yes'):
win = False
while(!win):
<your code for game, set win = True after winning>
play_again = input("Want to play again y or n: ").lower()
Edit: You can add failed along with win in the while loop as well.

'quit' command not working in python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
My problem here is when I ask if the player wants to play again, if they say no, I have it to where it's supposed to quit the script. but it doesn't seem to be working. Here's the full code:
def choose_level():
print("Please choose a level:\n"
"\n"
"(Level 1) - Easy\n"
"(Level 2) - Medium\n"
"(Level 3) - Hard\n")
lvl_1={"Level 1","level 1","1"}
lvl_2={"Level 2","level 2","2"}
lvl_3={"Level 3","level 3","3"}
choice=input("")
if choice in lvl_1:
level_1()
elif choice in lvl_2:
level_2()
else:
print ("[!] UNKNOWN LEVEL [!]\n")
choose_level()
def level_1():
import random #imports the module 'random'
yes={"Yes","Y","yes","y"} #set 'yes' to these 4 strings
no={"No","N","no","n"} #set 'no' to these 4 strings
name=input("What's your name?\n") #asks for a name
secret=int(random.random()*10)+1 #randomly generate a number
trynum=0 #sets the number of tries to 0
print ("---------------------------------------------------------------------\n"
"---- Welcome,",name+"! To Level 1!\n"
"---- I am thinking of a number between 1 and 10.\n"
"---- Lets see how many times it will take you to guess the number.\n"
"---------------------------------------------------------------------\n")
while True: #starts a loop
trynum=trynum+1 #sets number of tries to itself + 1
guess=int(input("What is guess #"+str(trynum)+"?\n")) #asks for a guess
if guess<secret: #if guess is too low/less than(<)
print ("Too Low. Try again!")
elif guess>secret: #if guess is too high/greater than(>)
print ("Oops!! Too high, better luck next try!")
else:
if trynum==1: #if number of tries is only 1
print ("-------------------------------------------------\n"
"----",name+"! You got it in",trynum,"guess!\n"
"-------------------------------------------------\n")
else: #if number of tries is anything else
print ("-------------------------------------------------\n"
"----",name+"! You got it in",trynum,"guesses!\n"
"-------------------------------------------------\n")
if trynum<3: #if guessed in less than 3 tries
print ("Bravo!")
elif trynum<5: #if guessed in less than 5 tries
print ("Hmmmmpf... Better try again")
elif trynum<7: #if guessed in less than 7 tries
print ("Better find something else to do!")
else: #if guessed in more than 7 tries
print ("You should be embarssed! My dog could pick better.")
choice=input("""Would you like to play again? ("yes" or "no")\n""") #asks if you want to play again
if choice in yes: #if yes, then run game again
choose_level()
if choice in no: #if no, then quit the game
print ("Okay.. Goodbye :(")
quit
break
def level_2():
import random
yes={"Yes","yes","Y","y"}
no={"No","no","N","n"}
name=input("What's your name?\n")
secret=int(random.random()*8)+1
trynum=0
print ("--------------------------------------------------------------------------\n"
"---- Welcome,",name+"! to Level 2!\n"
"---- I am thinking of a number between 1 and 8.\n"
"---- You have 20 guesses, and the number changes after every 4th guess\n"
"--------------------------------------------------------------------------\n")
while True:
trynum=trynum+1
guess=int(input("What is guess #"+str(trynum)+"?\n"))
if trynum==4:
secret=int(random.random()*8)+1
print ("The number has changed!!")
elif trynum==8:
secret=int(random.random()*8)+1
print ("The number has changed!!")
elif trynum==12:
secret=int(random.random()*8)+1
print ("The number has changed!!")
elif trynum==16:
secret=int(random.random()*8)+1
print ("The number has changed!!")
elif trynum==20:
print ("-------------------------------------------------\n"
"----",name+", you lost! :(\n"
"-------------------------------------------------\n")
choice=input("""Would you like to play again? ("yes" or "no")\n""") #asks if you want to play again
if choice in yes: #if yes, then run game again
choose_level()
elif choice in no: #if no, then quit the game
print ("Okay.. Goodbye :(")
quit
if guess<secret:
print ("Too low, try again!")
elif guess>secret:
print ("Too high, try again!")
else:
if trynum==1: #if number of tries is only 1
print ("-------------------------------------------------\n"
"----",name+"! You got it in",trynum,"guess!\n"
"-------------------------------------------------\n")
else: #if number of tries is anything else
print ("-------------------------------------------------\n"
"----",name+"! You got it in",trynum,"guesses!\n"
"-------------------------------------------------\n")
if trynum<3: #if guessed in less than 3 tries
print ("Bravo!")
elif trynum<5: #if guessed in less than 5 tries
print ("Hmmmmpf... Better try again")
elif trynum<7: #if guessed in less than 7 tries
print ("Better find something else to do!")
else: #if guessed in more than 7 tries
print ("You should be embarssed! My dog could pick better.")
choice=input("""Would you like to play again? ("yes" or "no")\n""") #asks if you want to play again
if choice in yes: #if yes, then run game again
choose_level()
if choice in no: #if no, then quit the game
print ("Okay.. Goodbye :(")
quit
break
choose_level()
level_1()
level_2()
The problem I'm having is here:
choice=input("""Would you like to play again? ("yes" or "no")\n""") #asks if you want to play again
if choice in yes: #if yes, then run game again
choose_level()
if choice in no: #if no, then quit the game
print ("Okay.. Goodbye :(")
quit
break
When I run the program and I get to that point, and type 'no' it just puts me back on the first level. I'm stuck and not sure where to go from here. Any and all help is appreciated.
You are missing the pair of brackets that come after the quit command. The quit command is calling a function just like choose_level does, so you need to tell Python what parameters you want to pass in. Every function call needs a pair of brackets telling Python what arguments you want. The quit function is no different. In this case, there will be no parameters so you would just type quit().
sys.exit() , exit() , quit() , and os._exit(0) kill the Python interpreter
You should use quit() , not quit

Does raw_input() stop an infinite while loop?

There is a small code below containing of while-loop.
question = raw_input("How are you? > ")
state = True
number = 0
print "Hello"
while True:
if question == "good":
print "Ok. Your mood is good."
state = False
question_2 = raw_input("How are you 2? > ")
elif question == "normal":
print "Ok. Your mood is normal."
elif question == "bad":
print "It's bad. Do an interesting activity, return and say again what your mood is."
else:
print "Nothing"
If I type in "normal", the program prints Ok. Your mood is normal. an infinite number of times.
But if I type in "good", the program prints Ok. Your mood is normal. and prints the contents of question_2.
Why is the question in question_2 = raw_input("How are you 2? > ") not repeated an infinite number of times?
Is it reasonable to conclude that raw_input() stops any infinite while loop?
No. It's not stopping the loop; it's actively blocking for input. Once input is received, it will not be blocked anymore (and this is why you get infinite text from other selections); there is no blocking I/O in those branches.
The reason you're not getting a lot of text output from option 1 is due to the way it's being evaluated. Inside of the loop, question never changes, so it's always going to evaluate to "good" and will continually ask you the second question1.
1: This is if it is indeed while True; if it's while state, it will stop iteration due to state being False on a subsequent run.
Once you've answered "good, the value returned by the second raw_input will be stored in variable question_2 rather than question. So variable question never changes again, but will remain "good". So you'll keep hitting the second raw_input, no matter what you answer to it. It doesn't stop your loop, but rather pauses it until you answer. And I think you should also take a good look at the comment of Alfasin...
You can stop an infinite loop by having an else or elif that uses a break for output. Hope that helps! :D
Example:
while True:
if things:
#stuff
elif other_things:
#other stuff
#maybe now you want to end the loop
else:
break
raw_input() does not break a loop. it just waits for input. and as your question is not overwritten by the second raw_input(), your if block will always end up in the good case.
a different approach:
answer = None
while answer != '':
answer = raw_input("How are you? (enter to quit)> ")
if answer == "good":
print( "Ok. Your mood is good.")
elif answer == "normal":
print( "Ok. Your mood is normal.")
# break ?
elif answer == "bad":
print( "It's bad. Do an interesting activity, return and say again what your mood is.")
# break ?
else:
print( "Nothing")
# break ?

Categories

Resources