Problem With Number Guessing Game Giving Wrong answer [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I recently made a number guessing game and whenever I guess or lower than the randomnum it will acuratley say if it is higher or lower but if you try to keep guessing it keeps spitting out the same answer even if you get it right. I even made the code print the answer troughout the code just to make sure the value doesnt change.
import random
randomnum = random.randint(1, 100)
print(randomnum)
number = 0
wttg = input("welcome to the guesing game! \ntype y to start!")
if wttg == ("y"):
playinp = input("Guess a number between 1 and 100! \nGet it right and you win!\nwould you like to play on easy mode? (10 guesses)\nor hard mode? (3 guesses) E/H")
else:
print("oops! Thats not a correct input! Restart the code to try again! :\\")
if playinp == ("e"):
guessnum = int(input("OK, easy mode selected \nGuess..."))
while number < 10:
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
break
else:
if guessnum > randomnum:
guessnum == int(input("Guess Lower"))
number = (number + 1)
if guessnum < randomnum:
guessnum == int(input("Guess Higher"))
number = (number + 1)
if number == 10:
print("You lost boohoo. what are you guna cry?")
elif playinp == ("h"):
guessnum = int(input("OK, hard mode selected \nGuess..."))
while number < 2:
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
break
else:
if guessnum > randomnum:
guessnum == int(input("Guess Lower"))
number = (number + 1)
if guessnum < randomnum:
guessnum == int(input("Guess Higher"))
number = (number + 1)
print(randomnum)
if number == 2:
print("You lost boohoo. what are you guna cry?")
else:
print("oops! Thats not a correct input! Restart the code to try again!:\\")

I created a working version of your code and I will summarize the changes that I made so you can replicate this on your own.
The reason why your code doesn't update the guessnum variable is because you're doing
guessnum == int(input("Guess Lower"))
The double equal sign, ==, is a comparison operator so you are only checking if guessnum is equivalent to the input. Instead, use a single equal sign = which assigns the value of the input to the guessnum variable.
First off, from a code cleanliness perspective, you don't need parenthesis around comparisons. So instead of if wttg == ("y"):, you can just do if wttg == "y":.
You had the right idea for using a while loop but you didn't finish that code. In the future, if you want to test your code without it breaking, you can use a python pass statement. I added a condition that checks if guessnum does not equal randomnum so that we can avoid using a break statement.
Instead of doing number = (number + 1), you can use the += operator which does the same thing but is a shorthand notation. More info here.
Last thing is I did playinp.lower() == "e" and playinp.lower() == "h". This makes sure that users can type in both capital letters and lowercase letters which makes your game more user-friendly.
I updated the range of random.randint() to (1, 101) because Python ranges are non-inclusive of the last number. For example, if you print (list(range(1,10)) you will get [1, 2, 3, 4, 5, 6, 7, 8, 9].
I made quite a few more changes so feel free to ask me any more questions. :D
import random
randomnum = random.randint(1, 101)
print(randomnum)
number = 0
wttg = input("welcome to the guesing game! \ntype y to start!")
if wttg == "y":
playinp = input("Guess a number between 1 and 100! \nGet it right and you win!\nwould you like to play on easy mode? (10 guesses)\nor hard mode? (3 guesses) [E/H]")
else:
print("oops! Thats not a correct input! Restart the code to try again! :\\")
if playinp.lower() == "e":
print("OK, easy mode selected")
guessnum = int(input("Guess..."))
number += 1
while number < 10 and guessnum != randomnum:
if guessnum > randomnum:
guessnum = int(input("Guess Lower"))
else: # guessnum < randomnum
guessnum = int(input("Guess Higher"))
number += 1
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
elif number == 10:
print("You lost boohoo. what are you guna cry?")
elif playinp.lower() == "h":
print("OK, hard mode selected")
guessnum = int(input("Guess..."))
number += 1
while number < 3 and guessnum != randomnum:
if guessnum > randomnum:
guessnum = int(input("Guess Lower"))
else: # guessnum < randomnum
guessnum = int(input("Guess Higher"))
number += 1
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
elif number == 3:
print("You lost boohoo. what are you guna cry?")
else:
print("oops! Thats not a correct input! Restart the code to try again!:\\")
Above, I replicated your code structure but if you want to make the code cleaner, you can use the following code
import random
randomnum = random.randint(1, 101)
print(randomnum)
number = 0
wttg = input("welcome to the guesing game! \ntype y to start!")
if wttg.lower() == "y":
playinp = input("Guess a number between 1 and 100! \nGet it right and you win!\nwould you like to play on easy mode? (10 guesses)\nor hard mode? (3 guesses) [E/H]")
else:
print("oops! Thats not a correct input! Restart the code to try again! :\\")
if playinp.lower() == "e" or playinp.lower() == "h":
print("OK, easy mode selected" if playinp.lower() == "e" else "OK, hard mode selected")
max = 10 if playinp.lower() == "e" else 3
guessnum = int(input("Guess..."))
number += 1
while number < max and guessnum != randomnum:
if guessnum > randomnum:
guessnum = int(input("Guess Lower"))
else: # guessnum < randomnum
guessnum = int(input("Guess Higher"))
number += 1
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
elif number == max:
print("You lost boohoo. what are you guna cry?")
else:
print("oops! Thats not a correct input! Restart the code to try again!:\\")

Inside of the if statements where you check if guessnum is lower or higher than randomnum, you aren't updating the value of guesnum. For example, if the guess is too high, you're doing guessnum == int(input("Guess Lower")) which just checks if guessnum is equal to the input or not. You want guessnum = int(input("Guess Lower")) which actually sets the value.

Related

Why doesn't the last line of this code work even when the conditions are met? This is from the book "Automate The Boring Stuff" [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 last month.
Improve this question
import random
secret_number = random.randint(1, 20)
print("I'm thinking of a number between 1 and 20")
for guesses_taken in range(1, 7):
guess = int(input("Take a guess"))
if guess < secret_number:
print("This number is too low")
elif guess > secret_number:
print("This number is too high")
else:
break
if guesses_taken == 6:
print(f"Nope, the number I was thinking about was {secret_number}")
#this line won't display even when the number is guessed correctly
if guess == secret_number and guesses_taken < 6:
print(f"Good job! You guessed my number in {guesses_taken} guesses!")
The original code had an indentation error, which I fixed by moving the last four lines of code to the loop teritory. Sadly, the last line still won't display even though the number was guessed correctly.
That's because you have indentation wrong. Everything below break should be unindented, so that it's not part of the for loop:
import random
secret_number = random.randint(1, 20)
print("I'm thinking of a number between 1 and 20")
for guesses_taken in range(1, 7):
guess = int(input("Take a guess"))
if guess < secret_number:
print("This number is too low")
elif guess > secret_number:
print("This number is too high")
else:
break
if guesses_taken == 6:
print(f"Nope, the number I was thinking about was {secret_number}")
if guess == secret_number and guesses_taken < 6:
print(f"Good job! You guessed my number in {guesses_taken} guesses!")
However, I would like to add that even this version of the code has a bug: if a user guessed correctly on his last attempt, the output would still be Nope, the number I was thinking about was {secret_number}
First of all you don't really need the
if guesses_taken == 6:
The problem you're having is probably the break statement is on the same indentation level as the
if guess == secret_number and guesses_taken < 6:
Here is your code that should work fine.
import random
secret_number = random.randint(1, 20)
print("I'm thinking of a number between 1 and 20")
for guesses_taken in range(1, 7):
guess = int(input("Take a guess"))
if guess == secret_number:
print(f"Good job! You guessed my number in {guesses_taken} guesses!")
break
elif guess < secret_number:
print("This number is too low")
else:
print("This number is too high")
else:
print(f"Nope, the number I was thinking about was {secret_number}")
You don't really need the < 6 check because this will happen when you exceed your for loops range which is from 1 till 7
TL;DR:
Remove lines 12-13
Lines 8 through 13:
if guess < secret_number:
print("This number is too low")
elif guess > secret_number:
print("This number is too high")
else:
break
Think about this logically:
If the guess is less than the chosen number, inform the user that their guess is too low
If the guess is greater than the chosen number, inform the user that their guess is too higher
Otherwise, break out of the loop (essentially ending the code)
The only time when the 3rd condition would be fulfilled is if the number isn't too high, and isn't too low. The number is only both not too high and not too low if the number is equal to the chosen number. The else statement is what's causing your issues. Remove it.
Try this code out to see if it solves your problem:
import random
secret_number = random.randint(1, 20)
print("I'm thinking of a number between 1 and 20")
for guesses_taken in range(1, 7):
guess = int(input("Take a guess"))
if guess < secret_number:
print("This number is too low")
elif guess > secret_number:
print("This number is too high")
elif guess == secret_number:
print(f"Good job! You guessed my number in {guesses_taken} guesses!")
else:
break
if guesses_taken == 6:
print(f"Nope, the number I was thinking about was {secret_number}")
#this line won't display even when the number is guessed correctly
if guess == secret_number and guesses_taken < 6:
print(f"Good job! You guessed my number in {guesses_taken} guesses!")

Python guessing game, my win condition prints win and loss

Im learning python and having a go at the guessing game. my game works but my win condition prints both "you win" and "you loss", I think my "if" statements are incorrect but i could be wrong.
Also, there's an issue with my printing of the win loss, I can only get it to print the loss..
Thanks in advance!
import random
print("Number guessing game")
name = input("Hello, please input your name: ")
win = 0
loss = 0
diceRoll = random.randint(1, 6)
if diceRoll == 1:
print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
print("You have 3 guesses.")
if diceRoll == 4:
print("You have 4 guesses.")
if diceRoll == 5:
print("You have 5 guesses.")
if diceRoll == 6:
print("You have 6 guesses.")
number = random.randint(1, 5)
chances = 0
print("Guess a number between 1 and 5:")
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
break
win += 1
elif guess < number:
print("Your guess was too low")
else:
print("Your guess was too high")
chances += 1
if not chances == 0:
print("YOU LOSE!!! The number is", number)
loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))
Try changing your loop. Since you're breaking if it's correct, you can use a while: else. Otherwise you can win on your last chance and still get the lose message.
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
break
win += 1
elif guess < number:
print("Your guess was too low")
else:
print("Your guess was too high")
chances += 1
else:
print("YOU LOSE!!! The number is", number)
loss += 1
In your while loop the if statement should be...
if guess == number:
print("Something)
win += 1
break
and the last if statement should be...
if win != 0:
print("You lose")
else:
print("You win")
The problem lies within the final if statement. The player loses if their chances are greater than the diceRoll, whereas the if condition is true if the player's chances are not 0 i.e. the player failed once.
The code for the final if statement should look something like this:
if chances >= diceRoll:
print("YOU LOSE!!! The number is", number)
loss += 1
As for the problems printing the win, the problem here is in the first if statement inside the while loop. If the player wins the break statement is encountered first, so the code breaks out of the while loop without incrementing the win counter.
Just swap the break statement with the win += 1 and it'll work wonders:
if guess == number:
print("Congratulation YOU WON!!!")
win += 1
break
To start look at
the position of your break
the loss condition

if goes through while closing

import random
answer = random.randrange(1,100)
guess = 101
while int(guess) != 0 :
guess = input('Enter a number between 1 and 100 or enter 0 to exit: ')
guess = int(guess)
if guess < answer :
print('Too low')
elif guess > answer :
print('Too high')
else:
print('Correct')
print('Game closed')
I have to make a random number guessing game and to close the game you enter 0 it is supposed to print game closed which it does however it also prints the if < since 0 is always going to be lower than the guess how would i get it to not include the if <
You need to rank your conditions in the order of preference. What takes the highest precedence? You'd want if guess == answer to be your first priority, because if that's the case then there's no need to check anything else and your program is done. What's your second priority? If 0 is typed then the game ends.
In other words, start with the more specific conditions (not something as broad as guess > answer).
Reframe your conditional statements as such:
if guess == answer:
print('Correct')
break
elif guess == 0:
print('Game closed')
elif guess > answer:
print('Too high')
else:
print('Too low')
You also need to set guess to 0 to break out of the loop (or just add a break as I've done here)
Re-formulate your code a bit:
import random
answer = random.randrange(1,100)
while True :
guess = int(input('Enter a number between 1 and 100 or enter 0 to exit: '))
if guess == 0:
print('Game closed')
break
elif guess < answer :
print('Too low')
elif guess > answer :
print('Too high')
else:
print('Correct!')
break

Python Random Guessing Game

Implement the GuessNumber game. In this game, the computer
- Think of a random number in the range 0-50. (Hint: use the random module.)
- Repeatedly prompt the user to guess the mystery number.
- If the guess is correct, congratulate the user for winning. If the guess is incorrect, let the user know if the guess is too high or too low.
- After 5 incorrect guesses, tell the user the right answer.
The following is an example of correct input and output.
I’m thinking of a number in the range 0-50. You have five tries to
guess it.
Guess 1? 32
32 is too high
Guess 2? 18
18 is too low
Guess 3? 24
You are right! I was thinking of 24!
This is what I got so far:
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput>randomNumber:
print(randomNumber + "is too high.")
elif userInput < randomNumber:
print(randomNumber + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
I've been getting a syntax error and I don't know how to make the guess increase by one when the user inputs the wrong answer like, Guess 1?, Guess 2?, Guess 3?, Guess 4?, Guess 5?, etc...
Since you know how many times you're going through the loop, and want to count them, use a for loop to control that part.
for guess_num in range(1, 6):
userInput = int(input(f"Guess {guess_num} ? "))
if userInput == randomNumber:
# insert "winner" logic here
break
# insert "still didn't guess it" logic here
Do you see how that works?
You forgot to indent the code that belongs in your while loop. Also, you want to keep track of how many times you guessed, with a variable or a loop as suggested. Also, when giving a hint you probably want to print the number guessed by the player, not the actual one. E.g.,
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
count = 0
while guessed is False and count < 5:
userInput = int(input("Guess 1?"))
count += 1
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput > randomNumber:
print(str(userInput) + " is too high.")
elif userInput < randomNumber:
print(str(userInput) + " is too low.")
if count == 5:
print("Your guess is incorrect. The right answer is" + str(randomNumber))
print("End of program")
You are facing the syntax error because you are attempting to add an integer to a string. This is not possible. To do what you want you need to convert randomNumber in each print statement.
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + str(randomNumber) + "!")
elif userInput>randomNumber:
print(str(randomNumber) + "is too high.")
elif userInput < randomNumber:
print(str(randomNumber) + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
import random
arr=[]
for i in range(50):
arr.append(i)
answer=random.choice(arr)
for trial in range(5):
guess=int(input("Please enter your guess number between 0-50. You have 5
trials to guess the number."))
if answer is guess:
print("Congratulations....You have guessed right number")
break
elif guess < answer-5:
print("You guessed too low....Try again")
elif guess > answer+5:
print("You guessed too high..Try again")
else:
print("Incorrect guess...Try again please")
print("the answer was: "+str(answer))
Just a three things to add:
The "abstract syntax tree" has a method called literal_eval that is going to do a better job of parsing numbers than int will. It's the safer way to evaluate code than using eval too. Just adopt that method, it's pythonic.
I'm liberally using format strings here, and you may choose to use them. They're fairly new to python; the reason to use them is that python strings are immutable, so doing the "This " + str(some_number) + " way" is not pythonic... I believe that it creates 4 strings in memory, but I'm not 100% on this. At least look into str.format().
The last extra treat in this is conditional assignment. The result = "low" if userInput < randomNumber else "high" line assigns "low" of the condition is met and "high" otherwise. This is only here to show off the power of the format string, but also to help contain conditional branch complexity (win and loss paths are now obvious). Probably not a concern for where you are now. But, another arrow for your quiver.
import random
from ast import literal_eval
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
win = False
for guess_count in range(1,6):
userInput = literal_eval(input(f"Guess {guess_count}: "))
if userInput == randomNumber:
print(f"You are right! I was thinking of {randomNumber}!")
win = True
break
else:
result = "low" if userInput < randomNumber else "high"
print(f"{userInput} is too {result}")
if win:
print ("YOU WIN!")
else:
print("Better luck next time")
print("End of program")

random number generator, number guess. What is wrong with my code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have this basic code and what I want it to do is choose a random number, then it would ask the user to input a number from 0 to 100, the would give back results based on the number, such as number is too low or high. I keep switching things around but always get an error, this for 2.7:
import random
randomNumber = random.randrange(0,100)
guess = -1
guess = int(input('Enter a number between 0 and 100: ')
guess != randomNumber:
if guess < randomNumber
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
print('You win!')
First, you define guess twice. Just define it once. There is no need to make guess be equal to -1 if that won't be the original value anyways. Second, I believe you want to use a while loop to keep checking if the user has guessed the correct number. In this case, add another guess into the while loop to allow the player to continue guessing and to keep proper syntax.
Don't let the player win always with another condition. Use colons after each if/elif statement as well. As you are comparing a string (the input) and an integer, change the input() to int(input()). The final code should be something like:
import random
randomNumber = random.randrange(0, 100)
guess = None # Define guess
while guess != randomNumber: # Create loop
guess = int(input("Enter a number between 0 and 100")) # Change guess
if guess < randomNumber:
print "Your guess is too low."
elif guess > randomNumber:
print "Your guess is too high."
elif guess == randomNumber:
print "You win!" # Win message under correct condition
break # Exit the loop as game is finished
You're missing a colon after your if statement. You're also printing You win! regardless of the outcome. Put that inside an else statement. You don't need this line guess != randomNumber:, and you don't need guess=-1, and finally you're missing a closing paren as mentioned in comments.
import random
randomNumber = random.randrange(0,100)
guess = None
while guess != randomNumber:
guess = int(input('Enter a number between 0 and 100: '))
if guess == randomNumber:
break
elif guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
print('You win!')
As usual, commenting your code reveals the error instantly
import random
# Pick a number between 0 and 99
randomNumber = random.randrange(0,100)
# initialize guess (hint: why?)
guess = -1
# Ask the user to guess a number (hint: balanced parentheses help)
guess = int(input('Enter a number between 0 and 100: ')
# What is this line supposed to be? Looks like the beginning of a loop here, but what kind?
guess != randomNumber:
# If the guess is less than the number, then tell the user
if guess < randomNumber
print('Your guess is too low.')
# Otherwise if the guess is higher than the number, tell the user
elif guess > randomNumber:
print('Your guess is too high.')
# Regardless, win the game. Wait whuh..?
print('You win!')
Try the following code:
import random
randomNumber = random.randrange(0,100)
guess = int(input("Enter a number between 0 and 100:"))
if guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
else:
print('You win!')
(EDIT - removed some unecessary lines)
missing some formatting, and there's a few lines (guess != randomNumber:) that don't really do anything (and in that case, the colon would cause a SyntaxError).
import random
randomNumber = random.randrange(0,100)
guess = int(input('Enter a number between 0 and 100: '))
if guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
else: # assuming you only want to print this if they guessed right
print('You win!')

Categories