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
Related
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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So I am creating a new simple game to practice my python programming, it is a point/score system that I wanted to implement. I also wanted to make it so it's intelligent by asking the user if it wants to play. So I have three problems at the moment, when I ask the user if it wants to play I wasn't sure what to do if they said no or "n" if they didn't want to play, instead what happens is that it just continues playing then crashes saying "n" is not defined. The second problem that I have is when the user puts the right answer for the random function I put print("You guessed it right!") but it just prints a bunch of them. My third and final problem is the point system, I wasn't sure if it executed after the million printed statements, but I'll see after I fix it.
Here is my game
import random
total_tries = 4
score = 0
print("Welcome to Guess the number game!")
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))
guess = int(input("I am thinking of a number between 1 and 20: "))
while n!= guess:
if guess < n:
total_tries - 1
print("That is too low!")
guess = int(input("Enter a number again: "))
elif guess > n:
print("That is too high")
total_tries - 1
guess = int(input("Enter a number again: "))
else:
break
while n == guess:
score = +1
print("You guessed it right!")
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
print("Mark:", str(mark) + ""%"")
print("Goodbye")
Error when putting no for playing:
while n!= guess:
NameError: name 'n' is not defined
For question 1 you want the system to exit when the user says no. I would do this by using sys.exit to kill the code.
import sys
...
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))**strong text**
else:
sys.exit('User does not want to play, exiting')
For problem 2 you are getting your print statement a million times because you're failing to exit. In the code below n is always equal to guess because you never change n. You don't need a while statement here because you already know you only left the above section when n started to equal guess. Another issue to think about. How will you make it stop when the number of turns runs out?
while n == guess:
score = +1
print("You guessed it right!")
For the third question, think about what will happen here if the number of turns reaches 0.
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
In particular, what would happen when you try to calculate mark?
This condition will only trigger when answer is "y"
if answer == "y":
n = (random.randrange(1, 10))
Remove this and the code will run or modify it as such
if answer == "y":
n = (random.randrange(1, 10))
elif answer == "n"
# set n to some other value
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
I'm trying to get this game to run ad infinitum until the user enters "q" or "quit". For some reason, this isn't quite working out with what I have. I initially tried to do this with two functions but failed miserably, so I consolidated for right now into one function to try to get it going. Still failing, but not as bad.
#Ex9: Guessing game. Generate a number between 1-9 and provide info whether its too high or low
import random
#print("Type q or quit to quit")
#guess = int(input("Please enter a number between 1 to 9: "))
def guessing_function():
while True:
quit1 = print("Type q or quit to quit")
guess = int(input("Please enter a number between 1 to 9: "))
value = random.randint(1,9)
if quit1 == "quit".lower() or "q".lower():
print("Ok we will stop")
break
elif guess > value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too high")
elif guess < value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too low")
elif guess == value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is correct!")
guessing_function()
Basically the issue is that the script just stops after one loop, rather than continue on without the user's input.... Not sure what I'm doing wrong.
Looks like you want to check if the user wanted to quit.
checking "quit".lower() is not correct. "quit" is already lower.
Also the or part of the if statement is incorrect. It will always be True.
Instead you want to check if lowercase of quit1 is either "quit" or "q".
You can do that by giving if quit1.lower() in ("quit","q"). By using in ("quit","q"), the if statement checks against the items in the tuple. This is a much better way to check when you have multiple values to check.
def guessing_function():
while True:
quit1 = print("Type q or quit to quit")
guess = int(input("Please enter a number between 1 to 9: "))
value = random.randint(1,9)
if quit1.lower() in ("quit","q"): #fixed this line
print("Ok we will stop")
break
elif guess > value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too high")
elif guess < value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too low")
elif guess == value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is correct!")
print doesn't prompt for user input(and returns None always), you should replace it with input instead.
The if is also wrong, it should be if quit1 == "quit" or quit1 == "q":. How to test multiple variables against a value? explains it better than I could.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I want to store a list of guesses the user has already made, so that when the user makes the next guess I can check that guess against a list of previous guesses. If the guess the user just made is in that list I want to tell the user to guess again and not count it as a attempt(5 attempts at guessing correct number)
tried using the append method to append the guesses to a blank list but I'm getting a "int obj has no append method" error.
import random
def guess_a_number():
chances = 5
random_number_generation = random.randint(1,21)
while chances != 0:
choice = int(input("Guess a number between 1-20, you only have {} chances left ".format(chances)))
if choice > random_number_generation:
print("Your number is too high, guess lower")
elif choice < random_number_generation:
print("Your number is too low, guess higher")
else:
print("You guessed the correct number!!!")
break
chances -= 1
if chances == 0:
try_again = input("Do you want to try play again? ")
if try_again.lower() == "yes":
guess_a_number()
else:
print("Better luck next time")
guess_a_number()
Try keeping a list of previous guesses and then check if guess in previous_guesses: immediately after the choice. You can use continue to skip the rest and prompt them again.
Just use a set or a list to hold the previously attempted numbers and check for those in the loop.
I think you already tried something similar but by the sound of it you were attempting to append to an int.
import random
while True:
chances = 5
randnum = random.randint(1, 21)
prev_guesses = set()
print("Guess a number between 1-20, you have {} chances ".format(chances))
while True:
try:
choice = int(input("what is your guess? "))
except ValueError:
print('enter a valid integer')
continue
if choice in prev_guesses:
print('you already tried {}'.format(choice))
continue
if choice > randnum:
print("Your number is too high, guess lower")
elif choice < randnum:
print("Your number is too low, guess higher")
else:
print("You guessed the correct number!!!")
break
chances -= 1
prev_guesses.add(choice)
print("you have {} chances left".format(chances))
if chances == 0:
print("You ran out of guesses, it was {}".format(randnum))
break
try_again = input("Do you want to play again? ")
if try_again.lower() not in ("y", "yes"):
print("Better luck next time")
break
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.