Sobhan
Sobhan

Reputation: 17

Why do I get "ValueError: invalid literal for int() with base 10". in this Python code?

I'm a beginner trying to improve my Python skills. I've found a very similar question to mine but since the source code was different, it did no benefit. Here is the link for the question: ValueError: invalid literal for int() with base 10: '' Anyways, here is my code:

correct_answer= 41
guess = int(input("Guess the number"))

if int(input()) == correct_answer:
print ("You found my number!")

if int (input()) >= correct_answer:
print ("My number is lower.")

if int (input()) <= correct_answer:
print ("My number is higher.")

else:
print ("You didn't write any numbers!")

Here, I wanted to write a simple guessing game. The number computer has in mind is 41, and the user has to guess the number after "Guess the number". If the input of a user is greater than 41, the program says "My number is lower" and if the input is smaller than 41, the program says "My number is greater." When I run this code, I get the "ValueError: invalid literal for int() with base 10: ''

Thank you in advance for helping me solve this problem :)

Upvotes: 0

Views: 1390

Answers (2)

Sushant
Sushant

Reputation: 3669

Try this -

correct_answer= 41
guess = raw_input("Guess the number")
try:
    guess = int(guess)
except ValueError:
    print "Wrong value entered"

if guess == correct_answer:
    print ("You found my number!")
elif....

Let me know if that helps

When you take the input and someone enters an alphabet or something which is not an integer, and you try to typecast it, python will throw a ValueError.

To catch such cases, we use try except block will catch it. More about python try except in python

Couple of pointers about your code -

if int(input()) == correct_answer:

here, you are just calling input() function and your program will not work, use variable guess, this is the variable you have put your input into.

and

if int(input()) == correct_answer:
print ("You found my number!")

if int (input()) >= correct_answer: 
print ("My number is lower.")

if int (input()) <= correct_answer:
print ("My number is higher.")

Use python's if elif elif else instead.

Also, since you have typecasted to integer already, you don't need to do that with every if condition, this would suffice -

if input > correct_answer and you don't need >= or <=.

>= means greater or equal, but you have handled the equal case in first condition, if it's equal, it'll be caught there, similar with less than or equal

Upvotes: 0

alexis
alexis

Reputation: 50220

The problem is that you are calling input() again and again. Everytime you do this, the program expects input and the user has to retype their guess in order for the program to work as intended. Replace all instances of int(input()) (with an empty prompt) with guess, and you'll see more reasonable behavior. E.g.

if guess == correct_answer:
    print ("You found my number!")

Upvotes: 1

Related Questions