Question

I read the answers to the Python questions on traceback errors, alas I don't understand the answers provided. When I run the below code I get a traceback error if the user enters nothing. How can I avoid it? Please give only specific and short answers. Thanks!

Error: Python Traceback Error: Invalid Literal for int() with base 10

def gold_room():
    print "This room is full of gold. How much do you take?"

    next = (raw_input(">>> "))
    how_much = int(next)

    if how_much < 50: 
        print "Nice, you're not greedy, you win!"
        exit(0)

    elif how_much > 50:
        print "You greedy bastard!"
        exit(0)
    else: 
        dead("Man, learn to type!")
Was it helpful?

Solution

In extension to Burhan Khalid's answer, if you want to prompt the user until he/she has entered a valid number, do this:

how_much = None
while how_much is None:
    next = (raw_input(">>> "))
    try:
       how_much = int(next)
    except ValueError:
       print "Dude, enter a value!"

OTHER TIPS

The reason you get that is when someone simply hits enter, the program gets a blank string '', and then the program tries to convert '' into int.

>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

So try this:

try:
   how_much = int(next)
except ValueError:
   dead("Dude, enter a value!")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top