This is my first post in this community and I am a beginner of course. I look forward to the day I can help others out. Anyway, this is the a simple code and I would like it so that there is an error if the user enters a string. Unfortunately, it does not execute the way I'd like to, here's the code:
number = 1
guess = int(input('Guess this number: '))
while True:
try:
if guess > number:
print("Number is too high, go lower, try again")
guess = int(input('Guess this number: '))
elif guess < number:
print("Too low, go higher, try again")
guess = int(input('Guess this number: '))
else:
print("That is correct")
break
except (SyntaxError, ValueError):
print("You can only enetr numbers, try again")
When the program gets executed, and it asks me to "Guess this number: ", when I write any string e.g. "d", it gives the error:
Guess this number: d
Traceback (most recent call last):
File "Numberguess.py", line 5, in <module>
guess = int(input('Guess this number: '))
ValueError: invalid literal for int() with base 10: 'd'
Thank you for your time and support.
Welcome to Stack Overflow! Everyone needs to start somewhere
Take a look at the code below:
# import random to generate a random number within a range
from random import randrange
def main():
low = 1
high = 100
# gen rand number
number = gen_number(low, high)
# get initial user input
guess = get_input()
# if user did not guess correct than keep asking them to guess
while guess != number:
if guess > number:
print("You guessed too high!")
guess = get_input()
if guess < number:
print("You guess too low!")
guess = get_input()
# let the user know they guess correct
print(f"You guessed {guess} and are correct!")
def gen_number(low, high):
return randrange(low, high)
# function to get input from user
def get_input():
guess = input(f"Guess a number (q to quit): ")
if guess == 'q':
exit()
# check to make sure user input is a number otherwise ask the user to guess again
try:
guess = int(guess)
except ValueError:
print("Not a valid number")
get_input()
# return guess if it is a valid number
return guess
# Main program
if __name__ == '__main__':
main()
This was a great opportunity to include Python's random module to generate a random number within a range. There is also a nice example of recursion to keep asking the user to guess until they provide valid input. Please mark this answer as correct if this works and feel free to leave comments if you have any questions.
Happy Coding!!!
Take a look at this line:
guess = int(input('Guess this number: '))
You try to convert string to int, it's possible, but only if the string represents a number.
That's why you got the error.
The except didn't worked for you, because you get the input for the variable out of "try".
By the way, there is no reason to input in the if, so your code should look like this:
number = 1
while True:
try:
guess = int(input('Guess this number: '))
if guess > number:
print("Number is too high, go lower, try again")
elif guess < number:
print("Too low, go higher, try again")
else:
print("That is correct")
break
except (SyntaxError, ValueError):
print("You can only enetr numbers, try again")
I would just use .isdigit(). The string would be validated at that point and then you would turn it into an int if validation works.
guess = input('Guess this number: ')
if guess.isdigit():
guess = int(guess)
else:
print("You can only enter numbers, try again")
Also worth to mention that try/excepts are cool and they get the job done, but it's a good habit to try to reduce them to zero, instead of catching errors, validate data beforehand.
The next example would do it:
number = 1
while True:
# Step 1, validate the user choice
guess = input('Guess this number: ')
if guess.isdigit():
guess = int(guess)
else:
print("You can only enter numbers, try again")
continue
# Step 2, play the guess game
if guess > number:
print("Number is too high, go lower, try again")
elif guess < number:
print("Too low, go higher, try again")
else:
print("That is correct")
break
the problem is in the first line. when you convert the input from the user directly to int, when a user inputs a letter, the letter cannot be converted to int, which causes the error message you get.
to solve this you need to do
guess = input('Guess this number: ')
if not guess.isdigit():
raise ValueError("input must be of type int")
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
import random
from random import randint
number = randint(1, 500)
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess)
while guess == number:
print("Congrats, you have won")
break
if guess > number:
print("Lower")
if guess < number:
print("Higher")
This code only allows the user to input one guess and then the program ends. Can someone help me fix this
You should think about your loop condition.
When do you want to repeat? This is the loop condition
When the guess is not correct. guess != number
What do you want to repeat? Put these inside the loop
Asking for a guess guess = int(input("Your guess: "))
Printing if it's higher or lower if guess > or < number: ...
What don't you want to repeat?
You need this before the loop
Deciding the correct number.
Setting the initial guess so the loop is entered once
You need this after the loop
Printing the "correct!" message, because you only exit the loop once the guess is correct
So we have:
number = random.randint(1, 100)
guess = 0
while guess != number:
guess = int(input("Your guess: "))
if guess > number:
print("Lower")
elif guess < number:
print("Higher")
print("Correct!")
Right now, your while loop is useless as once you are in it you break immediately. The rest of the code is not in a loop.
You should rather have an infinite loop with all your code, and break when there is a match:
from random import randint
number = randint(1, 500)
while True: # infinite loop
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess) # warning, this will raise an error if
# the user inputs something else that digits
if guess == number: # condition is met, we're done
print("Congrats, you have won")
break
elif guess > number: # test if number is lower
print("Lower")
else: # no need to test again, is is necessarily higher
print("Higher")
You must take input in the loop, because the value for each step has to be updated .
from random import randint
number = randint(1, 500)
while True:
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess)
if guess == number:
print("Congrats, you have won")
break
if guess > number:
print("Lower")
if guess < number:
print("Higher")
I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")
This question already has answers here:
ValueError: invalid literal for int() with base 10: 'stop'
(3 answers)
Closed 6 years ago.
Like many before me, I am brand new at this, so go easy if I haven't given all the information needed, and thank you in advance.
Before I start it's worth mentioning that the program itself is running fine, what i'm worried about is making sure I've thought of every possibly scenario. Here goes.
I'm receiving this error:
File "C:\Users\brand\Desktop\WIP Programs\Guess the number 31.July.py", line 15, in <module>
userGuess = int(input("I guess: "))
ValueError: invalid literal for int() with base 10: ' '
When I press the space bar for input, it returns this. I am not sure how to make it so that the program returns something useful, such as the ability to guess again. Here is my code, for reference:
import random
guessNum = 0
print("Welcome to the guess the number game! Please, tell me your name!")
user = input("My name is: ")
randNum = random.randrange(1, 10, 1) #Generates number
print("Okay, " + user + ", guess the random number, the range is 1 to 10.")
#Guessing phase
while guessNum < 3:
userGuess = int(input("I guess: "))
if userGuess > randNum:
print("Too high! Try again.")
guessNum = guessNum + 1
if userGuess < randNum:
print("Too low! Try again.")
guessNum = guessNum + 1
if userGuess == randNum:
print("Great! You guessed my number!")
break
else:
print("Please choose a valid answer.")
if userGuess == randNum:
print("If you would like to play again, please restart the program.")
if userGuess != randNum:
print("Nope. My number was: " + str(randNum))
If I have any unneeded or am lacking anything I should have, please feel free to correct me!
EDIT!
Going off of the first reply. I added .isdigit() into my code properly:
if (userGuess.isdigit()):
userGuess = input("I guess: ")
if userGuess > randNum:
print("Too high! Try again.")
guessNum = guessNum + 1
It keeps passing an exception saying that 'userGuess' is not defined. Fine! okay, So I define it in the beginning of my code next to user. Which upon running, returns
AttributeError: 'int' object has no attribute 'isdigit'
Also fine, so I add str(0) to userGuess to attempt a fix which then returns:
TypeError: unorderable types: str() > int()
It now lets me input a number, however I cannot figure out how to fix. Any advice?
When the user chooses a number, his input is returned as string.
Afterwards, you try to convert that string to an integer. This works fine for strings as "13" or "4", but doesn't for strings like " 3" or "2a". Therefore an exception is raised in such a case.
As workaround, you can check the string with the "isdigit()" method before converting it. That method will return True for strings containing only digits and False otherwise.
Your issue is that the line userGuess = int(input("I guess: ")) is converting to an integer value without checking if it's possible to do so. When it finds a character value, this will throw an exception since the conversion isn't possible.
You could prevent this with a try...catch but I think a better way is to use the isDigit() method to check if the value is only digits before you try and convert.
while guessNum < 3:
userGuess = input("I guess: ")
if (userGuess.isDigit()):
userGuess = int(userGuess)
if userGuess > randNum:
print("Too high! Try again.")
guessNum = guessNum + 1
...
if userGuess == randNum:
print("Great! You guessed my number!")
break
else:
print("Please choose a valid answer.")
Can someone please help me understand the following issue...
I'm having problems executing my try/except block in my simple number guessing game. The function containing my error handling works fine if I remove the integer portion of the initial input. But if I do this, the rest of the game doesn't work, because from my understanding Python3 takes input and stores it as a string. So how can I get my exception to execute? Any help is much appreciated.
Thanks,
# number game
import random
print ("Welcome to the guessing number game!\n\n")
winning_number= random.randrange(1, 11)
guess = int(input("Can you guess the lucky number.\nHint it's between 1 and 10!\n"))
def is_number(guess):
try:
int(guess)
except ValueError:
print ('You need to type a number\n')
guess = int((input("Please input a number\n")))
game(guess)
def compare(guess):
if guess > winning_number:
print ("Wrong, you're guess is too high.\n")
guess = int(input("Guess againn\n"))
game(guess)
else:
print ("Wrong, you're guess is too low.\n")
guess = int(input("Guess again\n"))
game(guess)
def game(guess):
is_number(guess)
if guess == winning_number:
print ("You win!, You guessed the number!")
else:
compare(guess)
game(guess)
Here is what I get when I input anything other than an integer...
Welcome to the guessing number game!
Can you guess the lucky number.
Hint it's between 1 and 10!
f
Traceback (most recent call last):
File "C:/Users/mickyj209/PycharmProjects/Practice/NumberGuess.py", line 10, in
guess = int(input("Can you guess the lucky number.\nHint it's between 1 and 10!\n"))
ValueError: invalid literal for int() with base 10: 'f'
Process finished with exit code 1
You forgot to save the value that time (guess = int(guess)), you're not returning anything there, and you're just having the program run the function but not making a decision based on the result. You also have an int(input(... in the exception handling, which could itself generate an exception which won't be caught. The initial guess isn't in a try block, either.
You could refactor this program:
def game():
print ("Welcome to the guessing number game!\n\n")
winning_number = random.randrange(1, 11)
print("Can you guess the lucky number?\nHint: it's between 1 and 10!\n")
while 1:
try:
guess = int(input("Please input a number\n"))
except ValueError:
continue
if guess > winning_number:
print('Wrong - your guess is too high.')
elif guess < winning_number:
print('Wrong - your guess is too low.')
else:
print('You win! You guessed the number!')
break
I am learning python and was writing this game, where the program picks a random number and asks the user to guess the number. In this case, a user can enter an empty string or an alphabet by mistake. So, i felt the need to check the type of the user input before doing the comparison as shown below. Also, this lead me to the following stackoverflow entry
Checking whether a variable is an integer or not
My question is why checking of types is considered a bad practice and how can i accomplish my task by not checking the type?
import random
num = random.randint(1,10)
while True:
guess = input('Guess a number between 1 and 10: ')
if(bool(guess)):
try:
guess = int(guess)
except:
print("Please enter a numeric value")
continue
else:
print("you have to enter some number")
continue
if guess == num:
print("you guessed it right")
break
elif guess < num:
print("Try higher")
elif guess > num:
print("Try lower")
As the comments have stated, at no point do you check the type. What you do is validate and convert the input, which is appropriate for this program (and indeed, should be used in any program that accepts user input).
Try this instead:
import random
num = random.randint(1, 10)
while True:
try:
guess = int(input('Guess a number between 1 and 10: '))
if guess == num:
print('You have guessed the correct number')
break
if guess < num:
print('Try higher.')
else:
print('Try lower.')
except ValueError:
print('Please enter a number.')
The idea is that simply converting the input and handling the error leads to much cleaner code. In Python circles, checking the type via isinstance is known as Look Before You Leap which is discouraged. Just attempt the operation in question and handle the failure case (usually by exception handling). This is termed Easier to Ask Forgiveness than Permission.