Reputation: 5
I am new to Python and am trying to make this interactive guessing game using Python 3. At ANY point in the game, if user just presses "Enter" without any input, it crashes to "ValueError: invalid literal for int() with base 10: ''" What do I add here?
Just to reiterate, I am new to programming. I am trying to code this entirely only using concepts I have learned so far, so everything is fairly basic.
# 'h' is highest value in range. 'a' is randomly generated value in the range. 'u' is user input
import random
h = 10
a = random.randint(1,h)
u = int(input("Please choose a number between 1 and %d. You can exit the game by pressing 0 anytime: " %(h)))
while u != a:
if 0 < u < a:
print("Please guess higher.")
u = int(input())
elif a < u < h:
print("Please guess lower.")
u = int(input())
elif u > h:
u = int(input("Whoa! Out of range, please choose within 1 and %d!" %(h)))
elif u == 0:
print("Thanks for playing. Bye!!")
break
# I was hoping to get the below response when user just presses "enter" key, without input
else:
print("You have to enter a number.")
u = int(input())
if u == a:
print("Well done! You got it right.")
Upvotes: 0
Views: 1860
Reputation: 186
That is happening because u = int(input()) always tries to convert whatever it was given into an integer. An empty string can not be converted to an integer -> you are getting this mistake. Now, python has try/except/else/finally clause exactly for this type of scenario. What I recon you should do is something like that
while True: #loop forever
try:
u = int(input("Please, enter a number: ")) #this tries to accept your input and convert it to integer
except ValueError: #executes if there is an error in try
print("That isn't a valid integer, please try again")
else:
print("u =",u)
break #break the loop if there was no mistakes in try clause
Upvotes: 0
Reputation: 3855
Your issue is that you're automatically converting the result of the input() call to an int, so if the user presses enter without actually entering a number, then your code will try to convert that empty string to an int, hence the error ValueError: invalid literal for int() with base 10: ''
. You could add a check to make sure that the user actually enters some input before converting it to an int directly, something like this:
u = input()
while u == '':
u = input('Please enter a number')
u = int(u)
However, this doesn't stop users from entering an invalid number, such as 'a' and causing a similar error, so a better solution to catch both of these issues could be:
u = ''
while type(u) != int:
try:
u = int(input("Please choose a number between 1 and %d. You can exit the game by pressing 0 anytime: " %(h)))
except ValueError:
pass
The try except catches that error that you were seeing earlier where the user enters something that doesn't resemble a number and the while loop repeats until the user enters a valid number
Upvotes: 1