Guess Random Number Why i m not able to enter input - python - 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).

Related

how to add an error message when an integer is input instead of a string

I am trying to add an error when a string is entered instead of an integer. I've looked at other similar posts but when I try and implement it into my code it keeps spitting errors out. I have a number guessing game between 1 and 50 here. Can't for the life of me figure out what's wrong.
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") )
break
except ValueError:
print("Please input a number.")**
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
Note that you're asking three times for the exact same input. There is really no need for that and no need for two loops at all. Just set the guess to a default value that will never be equal to the number (None) and use one single input, wrapped with try/except:
import random
number = random.randrange(1, 50)
guess = None
while guess != number:
try:
guess = int(input("Guess a number between 1 and 50: "))
except ValueError:
print("Please input a number.")
else:
if guess < number:
print("You need to guess higher. Try again.")
elif guess > number:
print("You need to guess lower. Try again.")
print("You guessed the number correctly!")
You could try running a while loop for the input statements. Checking if the input(in string format) is numeric and then casting it to int.
Sample code:
a = input()
while not a.isnumeric():
a = input('Enter a valid integer')
a = int(a)
The code executes until the value of a is an int
your code did not work because the indentation is not right
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") ) # here
break # here
except ValueError: # here
print("Please input a number.")
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
Output
Guess a number between 1 and 50: aa
Please input a number.
Guess a number between 1 and 50: 4
You need to guess higher. Try again.

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.

Why is the while loop creating an infinite loop? Guessing 1 and 100

I created a while loop so I would keep on asking the user questions until they got the number right. But when a do a random number, for example, it either prints "Pick a higher number" or "pick a lower number" infinitely. Can someone help me out here.
from random import randint
answer = randint(1, 100)
print("Guess a number between 1 and 3.")
guess = int(input())
count = 0
while guess != answer:
if guess < answer:
print("Pick a higher number.")
count += 1
elif guess > answer:
print("Pick a lower number.")
count += 1
elif guess == answer:
print("You got it!")
print("It took you " + str(count) + " tries.")
Try this.
while True:
guess = int(input("Guess a number between 1 and 3."))
if guess < answer:
print("Pick a higher number.")
count += 1
elif guess > answer:
print("Pick a lower number.")
count += 1
elif guess == answer:
print("You got it!")
break
Let me phrase it this way: When do you obtain the input from the user? What happens on a second loop run? Is guess at any time updated?
The answers to these (suggestive) questions will lead you to the right path:
You have to request input from the user in every loop run.
This will lead you to the point about how to start the loop.
from random import randint
answer = randint(1, 100)
count = 0
keep_loop = True
prompt = "Guess a number between 1 and 3."
while keep_loop:
print(prompt)
guess = int(input())
if guess < answer:
prompt = "Pick a higher number."
count += 1
elif guess > answer:
prompt = "Pick a lower number."
count += 1
elif guess == answer:
print("You got it!")
keep_loop = False
print("It took you " + str(count) + " tries.")

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