Bug with a program for a guessing game - python

I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a correct guess, you tell the user they are out of tries and tell them they lost. When the program finishes after a correct or 3 wrong tries and the game is over, you ask if the user wants to play again. If they say "yes", you star the game again and if they say "no", you end the game.
This is the code I have come up with:
import random
x =round(random.random()*5)
guess = False
tries = 0
while guess != True:
if tries<=3:
inp = input("Guess the number: ")
if tries<3:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! Try again."
tries = tries + 1
print "Your remaining tries are",(3-tries)
if tries>2:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
again = raw_input("Do you want to play again? ")
if again == "no":
print "Okay thanks for playing!"
elif again =="yes":
print "Great!"
Now when you guess the correct number before 3 tries, the program seems to be working fine, but even when the number of wrong tries exceeds 3, the program keeps asking for more guesses but I want it to stop the program right there. The second thing I don't get is how do I start the whole game again when the user wants to play again?
How can I modify my code to fix these errors?

The simplest way to stop a loop when some condition becomes true is to use break. So when the player guesses correctly, the code would look like
if inp == x:
guess = True
print "Correct! You won"
break
Additionally, you should break the loop when you run out of guesses, otherwise it will keep running
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
break
To let the player play again, you can have a variable playing and use it in a while loop that wraps the whole game, and when they say they don't want to play anymore, make it False so that the outer loop ends.
playing = True
while playing:
x = round(random.random()*5)
guess = False
tries = 0
while guess != True:
...
again = raw_input("Do you want to play again? ")
if again == "no":
print "Okay thanks for playing!"
playing = False
elif again =="yes":
print "Great!"
As you noted in comments on another answer, when the player gets their third guess wrong, the game tells them they have 0 guesses left and to try again, and then tells them they are out of tries and that the game is over. Since you want it to only tell them they are out of tries and that the game is over, you can change the main block of code to:
while guess != True:
inp = input("Guess the number: ")
if inp == x:
guess = True
print "Correct! You won"
else:
tries = tries + 1
if tries == 3:
print "Wrong guess! You are out of tries"
print "Game Over!"
break
else:
print "Wrong guess! Try again."
print "Your remaining tries are",(3-tries)

I guess this is it. Tested this out. Working Perfect (Y)
import random
x =round(random.random()*5)
guess = False
tries = 0
while guess != True:
if tries<=3:
inp = input("Guess the number: ")
if tries<3:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! Try again."
tries = tries + 1
print "Your remaining tries are",(3-tries)
if tries>2:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
again = raw_input("Do you want to play again? ")
if again == "no":
guess = True
print "Okay thanks for playing!"
elif again =="yes":
tries = 0
print "Great!"
Hope this helps.
Here's more compact code you can try. Also it is solving your "Wrong Guess. Try Again." issue on last guess.
import random
x =round(random.random()*5)
guess = False
tries = 0
print x
while guess != True:
while tries<3:
inp = input("Guess the number: ")
if inp == x:
guess = True
print "Correct! You won"
break
else:
tries = tries + 1
if tries == 3:
break
print "Wrong guess! Try again."
print "Your remaining tries are", (3 - tries)
if not guess:
print "Wrong guess! You are out of tries"
print "Game Over!"
again = raw_input("Do you want to play again? ")
if again == "no":
guess = True
print "Okay thanks for playing!"
elif again == "yes":
tries = 0
if guess:
guess = False
x = round(random.random() * 5)
print "Great!"

this is a slightly different version to your problem:
import random
def play():
x = round(random.random()*5)
guess = False
tries = 0
while guess is False and tries < 3:
inp = raw_input("Guess the number: ")
if int(inp) == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! Try again."
tries = tries + 1
print "Your remaining tries are",(3-tries)
if tries == 3:
print("Game Over!")
play()
again = "maybe"
while again != "no":
again = raw_input("Do you want to play again? yes OR no? \n")
if again == "yes":
print "Great!"
play()
print "Okay thanks for playing!"

You need to move where you set guess = True
import random
x =round(random.random()*5)
guess = False
tries = 0
while guess != True:
if tries<=3:
inp = input("Guess the number: ")
if tries<3:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! Try again."
tries = tries + 1
print "Your remaining tries are",(3-tries)
if tries>2:
guess = True
if inp == x:
print "Correct! You won"
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
again = raw_input("Do you want to play again? ")
if again == "no":
print "Okay thanks for playing!"
elif again =="yes":
print "Great!"
Before you were only ending on the condition where the last guess was correct. You should be ending whether the guess was correct or not.

You need to make guess equal to True in your second else or else it will never satisfy stop condition for while loop. Do you understand?
import random
x =round(random.random()*5)
guess = False
tries = 0
while guess != True:
if tries<=3:
inp = input("Guess the number: ")
if tries<3:
if inp == x:
guess = True
print "Correct! You won"
elif tries+1 != 3:
print "Wrong guess! Try again."
print "Your remaining tries are",(3-(tries+1))
tries = tries + 1
if tries>2:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
guess= True
again = raw_input("Do you want to play again? ")
if again == "no":
print "Okay thanks for playing!"
elif again =="yes":
print "Great!"
guess = False
tries = 0
EDIT: I think this does the trick using your code.

You need to update tries. Additionally you need to break out of your loop even if guess != True
import random
x =round(random.random()*5)
guess = False
tries = 0
while guess != True:
if tries<=3:
inp = input("Guess the number: ")
if tries<3:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! Try again."
tries = tries + 1
print "Your remaining tries are",(3-tries)
if tries>2:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
break
tries += 1
again = raw_input("Do you want to play again? ")
if again == "no":
print "Okay thanks for playing!"
elif again =="yes":
print "Great!"

Related

Guessing Game - Prompt the user to play again

I'm making a guessing game, but I want to add another line of code where the user can play again after, but I don't know where to start.
print ("Welcome to the Number Guessing Game in Python!")
# Initialize the number to be guessed
number_to_guess = 7
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int (input ("Please guess a number between 1 and 10: "))
while number_to_guess != guess:
print ("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
break
elif guess < number_to_guess:
print ("Your guess was lower than the number.")
else:
print ("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input ("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print ("Well done you won!")
print ("You took" + str(count_number_of_tries) + "attempts to complete the game.")
else:
print ("Sorry, you lose")
print ("The number you needed to guess was " + str(number_to_guess) + "." )
print ("Game Over.")
I dont know if the code should be at the bottom or in between somewhere.
I also want to remove the break if possible.
Great idea! In my mind, there are two ways of continuously asking the user to play until they enter something that will let you know they want to stop like 'q', 'quit', or 'exit'. First you could nest all of your current code a while loop (indent and write 'while(): before the code), or turn your current code into a function, and call it over and over again until the user enters the exit command
Ex:
lets say i can print hello world like this
# your game here
but now I want to keep printing it until the user enters 'quit'
user_input = '.' # this char does not matter as long as it's not 'quit'
while user_input != 'quit': # check if 'user_input' is not 'quit'
# your game here
user_input = input('Press any key to continue (and enter) or write "quit" to exit: ') # prompt user to enter any key, or write quit
Put all of that code in a game() function.
Underneath, write
while True:
game()
play=int(input('Play again? 1=Yes 0=No : '))
if play == 1:
pass
else:
break
print("Bye!")
I think this should do it, just a basic while loop
playAgain = 'y'
while playAgain == 'y':
print ("Welcome to the Number Guessing Game in Python!")
# Initialize the number to be guessed
number_to_guess = 7
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int (input ("Please guess a number between 1 and 10: "))
while number_to_guess != guess:
print ("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
print("You've guessed more than three times, you're pretty bad")
elif guess < number_to_guess:
print ("Your guess was lower than the number.")
else:
print ("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input ("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print ("Well done you won!")
print ("You took " + str(count_number_of_tries) + " attempts to complete the game.")
else:
print ("Sorry, you lose")
print ("The number you needed to guess was " + str(number_to_guess) + "." )
print ("Game Over.")
playAgain = (input ("Type y to play again, otherwise press enter: "))
print("Goodbye gamer")
You can add a while loop to the outermost layer that randomly generates the value of number_to_guess on each startup. And ask if you want to continue at the end of each session.
import random
print("Welcome to the Number Guessing Game in Python!")
number_range = [1, 10]
inp_msg = "Please guess a number between {} and {}: ".format(*number_range)
while True:
# Initialize the number to be guessed
number_to_guess = random.randint(*number_range)
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int(input(inp_msg))
while number_to_guess != guess:
print("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
break
elif guess < number_to_guess:
print("Your guess was lower than the number.")
else:
print("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print("Well done you won!")
print("You took" + str(count_number_of_tries) + "attempts to complete the game.")
else:
print("Sorry, you lose")
print("The number you needed to guess was " + str(number_to_guess) + ".")
if input("Do you want another round? (y/n)").lower() != "y":
break
print("Game Over.")

How do I stop this from repeating?

I am new to coding. It works alright until you guess a number. then it says either higher or lower eternally. Please help me understand what I've done wrong. I have tried searching the internet and trying to retype some of the code but it won't work. I am trying to make a conversation as well as a mini guess the number game.
Here's my Code
# Conversation A
import random
print("Answer all questions with 'yes' or 'no' and press ENTER")
print('Hello I am Jim the computer')
z = input('How are you? ')
if z == 'Good' or z == 'Great' or z == 'good' or z == 'great':
print("That's great!")
else:
print("Oh. That's sad. I hope you feel better.")
a = input("what's your name? ")
print(a + "? Thats a nice name.")
b = input('Do you own any pets? ')
if b == 'yes' or b == 'Yes':
print("That's cool. I love pets!")
else:
print("That's a shame, you should get a pet. ")
c = input("Do you like animals? ")
if c == 'yes' or c == 'Yes':
print("Great! Me too!")
else:
print("Oh that's sad. They're really cute. ")
d = input("Do you want to see a magic trick? ")
if d == "yes" or d == "Yes":
input("Ok! Think of a number between 1-30. Do you have it? ")
print("Double that number.")
print("Add ten.")
print("Now divide by 2...")
print("And subtract your original number!")
y = input("Was your answer 5? ")
if y == 'yes' or y == 'Yes':
print("Yay i got it right! I hope you like my magic trick.")
else:
print("Oh that's sad. I'll work on it. I really like magic tricks and games.")
else:
print("Ok. Maybe next time. I love magic tricks and games!")
e = input("Do you want to play a game with me? ")
if e == "yes" or e == "Yes":
randnum = random.randint(1,100)
print("I am thinking of a number between 1 and 100...")
if e == 'no' or e == 'No':
print("oh well see you next time" + a + '.')
guess = int(input())
while guess is not randnum:
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
if guess < randnum:
print("Higher.")
if guess > randnum:
print("Lower.")
You need to add a break statement when you want stop looping and move the input for guess inside the loop so you don't exit before printing the statement:
while True:
guess = int(input())
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
break
Edit: Also, you dont want to use is every time: Is there a difference between "==" and "is"?

How to loop the program back to the beginning with user input

I'm setting up a basic hangman game and am trying to get the program to loop back to the beginning when the game is finished.
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
print("Play Again? (y/n)")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
print("Play again? (y/n)")
Wrap your game in a function and throw it in a while loop.
After the play game function, they'll be asked to play again. If they respond with anything but 'y', the loop breaks.
while True:
# play_game()
if input("Play again?") != 'y':
break
print("Thanks for playing!")
You can use an user input and a while loop
play_again = "Y"
while play_again == "Y" or play_again == "y":
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
print("Play Again? (y/n)")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
play_again = input("Play again? (Y/N)")
or in short just put in in a function:
play_again = "Y"
while play_again == "Y" or play_again == "y":
game()
play_again = input("Play again? (Y/N)")
You could put it all into a function and have it loop back like this:
def start():
replay = True
while (replay):
game_started()
inp = input("Play again? Y/n ")
if inp == 'n' or inp == 'N':
replay = False
def game_started():
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
break
start()
Edit:
Your check if a letter was guesses is also flawed:
If you guess "abcdefghijklmnopqrstuvwxyz", you always win.
I'd suggest checking the length of the input before appending it to guesses.
Also, to print it all into one line, you could use "print(char, end='')" (and "print('_', end='')", respectively). Just make sure to print a newline after the loop, to finish the line.
Hey friend here is what I came up with I hope it helps! Instead of using your turns to control the while loop you can use a "running" variable that is set to a boolean which you can use input statements for your replay feature to control when you want to exit (False) or continue through your loop (True).
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
running = True
while running:
failed = 0
for char in word:
if char in guesses:
print(char),
else:
print("_"),
failed += 1
if failed <= 0:
print("You won")
x = input("Play Again? (y/n) \n")
if x == "y":
turns = 10
else:
running = False
guess = input("Guess a character: \n")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
z = input("Play Again? (y/n) \n")
if z == "y":
turns = 10
else:
running = False

Calling a function in an if statement?

I'm trying to write an if statement where if the user enters "yes" a game runs but when I cannot figure out how to do this, I can't find it online.
userName = input("Hello, my name is Logan. What is yours? ")
userFeel = input("Hello " + userName + ", how are you? ")
if userFeel == "good":
print ("That's good to hear")
elif userFeel == "bad":
print ("Well I hope I can help with that")
q1 = input("Do you want to play a game? ")
if q1 == "yes":
print ("Alright, lets begin")
import random
print ("This is a guessing game")
randomNumber = random.randint(1, 100)
found = False
yes = "yes"
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == randomNumber:
print ("You got it!")
found = True
elif userGuess>randomNumber:
print ("Guess Lower")
else:
print ("Guess Higher")
elif game == "no":
print ("No? Okay")
q2 = input("What do you want to do next? ")
This is because you have named both your variable for your input "game" and your function call "game". rename one or the other and your code should work as intended.
If you are using Python2.*, You should use raw_input instead of input.
And no matter what version of Python you are using, you should not use the same name for both the function and your variable.

Number guessing game does not recognize correct answer after 1st guess

If you do not guess the number correctly on the first try, the program will run until you run out of guesses regardless if you guessed the correct number. Is there a problem with my while loop or if statements?
while True:
try:
Guessed_number = int(raw_input("What is your guess? \n"))
except ValueError:
print("Sorry, that is not a valid guess. Please guess again.")
continue
else:
break
def Number_guesser(Guessed_number):
guesses= 3
while guesses > 0:
if Random_number == Guessed_number:
print "Congratualations! You won :)"
break
elif Guessed_number > Random_number:
print "You guessed higher than the number. Try again! \n"
print Random_number
Guessed_number= raw_input()
guesses= guesses-1
elif Guessed_number < Random_number:
print "You guessed lower than the number. Try again! \n"
Guessed_number= raw_input()
guesses= guesses-1
if guesses == 3:
print "You have 3 guesses left!"
elif guesses == 2:
print "You have 2 guesses left!"
elif guesses == 1:
print "You have 1 guess left!"
elif guesses == 0:
print "You ran out of guesses :( \n The correct answer was........*drum roll*"
print Random_number
print Number_guesser(Guessed_number)`
I figured out that my raw_input needed to be an integer every time I prompted the player to guess again.
Guessed_number= int(raw_input())

Categories