Python Print Error

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Wed Jul 27 01:54:37 EDT 2016


Cai Gengyang writes:

> How to debug this error message ?
>
> print('You will be ' + str(int(myAge) + 1) + ' in a year.')
> Traceback (most recent call last):
>   File "<pyshell#53>", line 1, in <module>
>     print('You will be ' + str(int(myAge) + 1) + ' in a year.')
> ValueError: invalid literal for int() with base 10: ''

The last line is the error message:

    ValueError: invalid literal for int() with base 10: ''

It's first component, ValueError, names a class of errors. It gives you
an idea (once you get used to error messages) of what might be wrong.

The second component describes this particular error:

    invalid literal for int() with base 10

This refers to the argument to int(), and says it's an invalid
"literal", which is a bit obscure term that refers to a piece in
programming language syntax; it also informs you that the argument is
invalid in base 10, but this turns out to be irrelevant.

You should suspect that myAge is not a string of digits that form a
written representation of an integer (in base 10).

The third component shows you the invalid literal:

    ''

So the error message is telling you that you tried to call int(''), and
'' was an invalid thing to pass to int().

(Aside: Do not take "int()" literally. It's not the name of the
function, nor is it the actual call that went wrong. It's just a
shorthand indication that something went wrong in calling int, and the
argument is shown as a separate component of the message.)

Next you launch the interpreter and try it out:

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

You can be pretty confident that the error is, indeed, just this. - Try
also int('ace') and int('ace', 16). That's where "base 10" is relevant.

The lines before the last are the traceback. They attempt to give you an
indication of where in the program the offending piece of code occurs,
but they need to do it dynamically by showing what called what. Scan
backwards and only pay attention to lines that you recognize (because
you are not studying an obscure bug in Python itself but a trivial
incident in your own program).

Often it happens that the real error in your program is somewhere else,
and the exception is only a symptom. In this case, you need to find
where myAge gets that value, or fails to get the value that is should
have.



More information about the Python-list mailing list