Wrong Output Guess the Number - python

I'm making a small game that chooses a random number in the given limit and the user tries to guess the number. I tried to add chances so you could try multiple times. Why is it returning the guessed number multiplied by the chance number?
def guessTheNumber():
chances = int(input('How many chances do you want: '))
limit = int(input('Input limits: '))
inputnum = int(input('Input number: '))
x = 1
while x <= chances:
randomnum = randomNum(limit)
if inputnum == randomnum:
print('you won!')
x+=1
continue
else:
print('THe number was {}'.format(randomnum))
replay()
When called it returns:
guessTheNumber():
How many chances do you want: 3
Input limits: 10
Input guess: 4
you won!
you won!
you won!
The number was 4
play again?: no
Goodbye

It loops until you have won 'chances' times. Look at the indent of the various lines.

You have the game backwards. The user is selecting a number once, and then the computer guesses every time through the loop.
You're only incrementing x when the computer guesses right, because x += 1 is in the if block, and you don't stop the loop when the guess is correct. So you'll get chances You won messages, then the loop stops.
The correct code is:
def guessTheNumber():
chances = int(input('How many chances do you want: '))
limit = int(input('Input limits: '))
randomnum = randomNum(limit)
x = 1
while x <= chances:
inputnum = int(input('Input number: '))
if inputnum == randomnum:
print('you won!')
break
x+=1
else:
print('The number was {}'.format(randomnum))
replay()

Related

How do I fix this guessing game of numbers 1 - 50?

The following project requires: Your program should implement a simple guessing game with the following requirements:
Generate a random number between 1 and 50 and then have the user guess the number. The program should tell the user whether they have guessed too high or too low and allow them to continue to guess until they guess the number or enter a 0 to quit.
When they guess the number it should tell them how many guesses it took. At the end, the program should ask them if they want to play again.
For example:
Enter a guess 1-50, or 0 to quit: 25
Too high!
Enter a guess 1-50, or 0 to quit: 15
Too low!
Enter a guess 1-50, or 0 to quit: 100
Guess must be between 1 and 50!
Enter a guess 1-50, or 0 to quit: 18
That's it! You took 3 guesses to get the number.
Would you like to play again? (Y/N)
I currently have everything settled except for two issues. I cannot seem to get the play again feature to work and for some reason the first number that is guessed will not say whether it is too low or too high.
My following code:
import random
play = True
randomNum = 45 #random.randrange(1,50)
guesses = 1
num = int(input())
print("Enter a guess 1-50, or 0 to quit:", num)
if num > 50 or num < 1:
print('Guess must be between 1 and 50!')
if num == randomNum:
print("That's it! You took", guesses, "guess to get the number.")
#print("Guess must be between 1 and 50!")
while num != randomNum:
guesses += 1
num = int(input())
print("Enter a guess 1-50, or 0 to quit:", num)
if num == 0:
break
elif num > 50 or num < 1:
print('Guess must be between 1 and 50!')
elif num > randomNum:
print("Too high!")
elif num < randomNum:
print("Too low!")
if num == randomNum:
print("That's it! You took", guesses, "guesses to get the number.")
print("Would you like to play again? (Y/N)")
letter = str(input())
if letter != 'Y':
play = False
I explained above what I have tried. I do believe that the issue is that the first guess does not enter the while loop. Unsure of how to fix this though.
First issue is that your while cycle only lasts until a number is guessed. So that means after you guess the first random number, your program will finish.
In order to avoid that you should declare your $play = True$ boolean on top of the cycle so you can declare your while cycle something like this:
play = True
while play:
# game goes here.
print("Would you like to play again? (Y/N)")
letter = str(input())
if letter != 'Y':
play = False
Then your cycle should continue while letter is Y or play remains True.
Second issue is that you ask for the number outside the cycle. That is not necessary, you can ask it inside after you construct your code like the example above.
I hope this clears things up.
ps. This is my first answer, so please point out if I did something wrong!

Python: Can't figure out why my loop skips the right answer

I decided to make a small project to test my skills as I continue to learn Python in my free time.
The game consists of the user guessing the right number that is randomly generated within a certain amount of tries. The user first enters the range of numbers they want to guess from. Then they get their first try at guessing the right number (I have the randomly generated number displayed on purpose to test my code as I continue). I cannot figure out why when I enter the same number as the randomly generated number, I get the error that would pop up when you guess the wrong number. But if I enter that same number after I am prompted to guess for the randomly generated number again, I get a success note prompted to me. I've been trying different variations all day.
import random
print("Guessing Game")
rangeAmount = int(input("From 1 to what number do you want to guess from (Maximum amount is 50)? "))
correctNum = random.randint(1, rangeAmount)
wrongCount = 0
userScore = 0
print("-" * 50)
while rangeAmount:
if 1 < rangeAmount < 10:
guesses = 3
print("Guesses allowed: 3")
break
if 1 < rangeAmount < 20:
guesses = 4
break
if 1 < rangeAmount < 30:
guesses = 5
break
if 1 < rangeAmount < 40:
guesses = 6
break
if 1 < rangeAmount < 50:
guesses = 7
break
print("Correct number: " + str(correctNum))
print("Guess amount: " + str(guesses))
print("-" * 50)
userGuess = input("Make a guessing attempt for the correct number: ")
while userScore != 3:
if wrongCount != guesses:
if userGuess is correctNum:
userScore += 1
print("You got the right answer")
break
else:
wrongCount += 1
print("Current guess count: {}".format(wrongCount))
userGuess = int(input("Wrong answer, try again: "))
if wrongCount == guesses:
print("Out of guesses, score is : {}".format(userScore))
userScore -= 1
break
if userScore == 3:
print("You won the game!")
Output:
Guessing Game
From 1 to what number do you want to guess from (Maximum amount is 50)? 23
--------------------------------------------------
Correct number: 5
Guess amount: 5
--------------------------------------------------
Make a guessing attempt for the correct number: 5
Current guess count: 1
Wrong answer, try again: 5
You got the right answer
Process finished with exit code 0
First, your maximum range is 50, but it is not included in your first while loop (ends at 49), change the last line to <= 50. You can remove the while loop, and change the if statements to if/elifs. Second, your indentation is off in the while userScore != 3: loop, but that could just be a copy/paste error.
And now for the most likely cause of the error,
userGuess = input("Make a guessing attempt for the correct number: ")
is a string, don't forget to make it an int before you compare it to another int.

How to fix guessing game

The objective is to create a simple program that generates a number between 1 and 100, it will then ask the user to guess this, if they guess outside of the number range it should tell them to guess again, if not it should tell them whether their guess was too high or too low, prompting them to guess again. Once they do guess the correct number it should tell them they've won and the number of tries it took for them to guess it correctly.
Here is what I have so far
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
return play_game
else:
print("Invalid number.")
return play_game()
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
play_game()
The issue I'm currently running into is when it checks to see if their guess was between 1-100 instead of moving on to weather or not their number was too how or to low, it stays and loops.
If anyone could help me with this issue and review the code in general I'd appreciate it.
I think the problem is with some indentation and some logical problems in the flow.
When you call play_game() from inside the game, it starts a completely different game
with different random_number.
A good code that satisfies your condition might look like the following
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
else:
print("Invalid number.")
play_game()
You could re-adjust your code:
1. if no. within range, run your high, low, match checks
2. break if guess matches the no
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 0
while True:
count += 1
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
break
else:
print("Invalid number, try again")
play_game()
The issue you are running into is because of incorrect indentation. The if-else statements that check whether the number is within the valid range are at the same indentation level as the while loop and thus are not executed within it. Simply indenting should fix the problem.
Furthermore, you have called play_game without parenthesis, making it incorrect syntax for a function call. However, rather than checking if the number is greater than 0 and lesser than 100, it would more optimal to check whether number is lesser than 0 or greater than 100, and if that is the case, print invalid number and call play_game().
It would look something like this:
while True:
if guess < 0 and guess > 100:
print ("Invalid number.")
return play_game()
The rest of your code looks good. I've also attached the link on the section of indentations of the Python documentation here.

Guess Random Number Why i m not able to enter input - python

Below is my code to generate random number between 0 - 9 and checking with user input whether it is higher lower or equal. When I run the code, it is not taking input and showing
error in 'guessNumber = int(input("Guess a Random number between 0-9")) File "", line 1 '
Can somebody please tell me where I'm making mistake
#Guess Random Number
#Generate a Random number between 0 to 9
import random
turn = 0
def guessRandom():
secretNumber = random.randint(0,9)
guessNumber = int(input("Guess a Random number between 0-9"))
while secretNumber != guessNumber:
if(secretNumber > guessNumber):
input("You have Guessed the number higher than secretNumber. Guess Again!")
turn = turn + 1
elif (secretNumber < guessNumber):
input("You have guessed the number lower than secretNumber. Guess Again! ")
turn = turn + 1
if(secretNumber == guessNumber):
print("you Have Guessed it Right!")
guessRandom()
I think guessRandom() was meant to be outside of the method definition, in order to call the method. The guessNumber variable never changes since the inputs are not assigned to be guessNumber, thus it will continuously check the initial guess. Also, the less than / greater than signs seem to conflict with the intended message. Additionally, turn is outside of the scope of the method.
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = int(input("Guess a Random number between 0-9: "))
i = 0
while secretNumber != guessNumber:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
guessNumber = int(input("Guess Again! "))
return i
turn = 0
turn += guessRandom()
EDIT: Assuming you're using input in Python3 (or using raw_input in older versions of Python), you may want to except for ValueError in case someone enters a string. For instance,
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = input("Guess a Random number between 0-9: ")
i = 0
while True:
try:
guessNumber = int(guessNumber)
except ValueError:
pass
else:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
break
guessNumber = input("Guess Again! ")
return i
turn = 0
turn += guessRandom()
I changed the while loop condition to True and added a break because otherwise it would loop indefinitely (comparing an integer to a string input value).

Python Number Guessing Game Need Help Avoiding Counting Duplicates in "Number of Guesses"

I am brand new to learning Python and am building a very simple number guessing game. The user guesses a number between 1-100, and are given feedback on whether their guess is too low or too high. When they guess the number correctly, the program tells them how many guesses they took. What I need help with: telling the user when they guessed a duplicate number if they have entered it already. I also want to exclude any duplicate guesses from the final guess count. What is the easiest way to do this?
Here is my game so far:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
guess = int(input(""))
tries = 0
while guess != the_number:
if guess > the_number:
print("Lower")
if guess < the_number:
print("Higher")
guess = int(input("Guess again: "))
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
Keep track of the numbers guessed, only increasing if the user has not guessed a number already in our guessed set:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
tries = 0
# store all the user guesses
guessed = set()
while True:
guess = int(input("Guess a number: "))
# if the guess is in our guesses set, the user has guessed before
if guess in guessed:
print("You already guessed that number!")
continue
# will only increment for unique guessed
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
elif guess > the_number:
print("Lower")
# if it's not == or >, it has to be <
else:
print("Higher")
# add guess each time
guessed.add(guess)
You also had some logic in regard to your ordering like taking a guess outside the loop which could have meant you never entered the loop if the user guessed first time.
this is how you should write the code.
import random
debug = True
def number_guessing():
previous_guesses = set()
tries = 0
print("Guess a number between 1-100")
random_number = random.randint(1, 100)
while True:
guess = int(input())
if guess in previous_guesses:
print("You already tried that number")
continue
previous_guesses.add(guess)
tries += 1
if random_number < guess:
print(f"Lower => previous attempts [{previous_guesses}] tries [{tries}]") if debug is True else None
elif random_number > guess:
print(f"Higher => previous attempts [{previous_guesses}] tries [{tries}]") if debug is True else None
elif guess == random_number:
print("You win! The number was", random_number)
print(f"And it only took you {tries} attempt{'s' if tries>1 else ''}!\n")
break
number_guessing()

Categories

Resources