Issue converting to string to integer.

alex23 wuwei23 at gmail.com
Sun Jun 2 22:02:23 EDT 2013


On Jun 3, 11:12 am, Fdama <fsd... at gmail.com> wrote:
> I combined the int conversion and the input on the same line, rather than to have two different statements. But  got an error message:
>
> Traceback (most recent call last):
>   File "C:\Users\Faisal\Documents\python\pizza_slicer.py", line 23, in <module>
>     start=int(input("\nStart: "))
> ValueError: invalid literal for int() with base 10: ''
>
> Could someone tell me why I got this error message?

When you were presented the 'Start' prompt, you hit Enter, which
causes `input` to return an empty string.  As it's passed directly
into `int`, which requires a valid string-representing-a-number, you
get the ValueError traceback, which shows you the failing input it
received: '' This doesn't happen in your original code, because your
condition `if start:` will fail on an empty string, and not try to
turn it into an int.

You don't want to wrap your `input` with an `int`. You want to test
the return result from `input` to ensure it can be coerced:

    start = input("\nStart: "))
    if start and start.isdigit():
        start=int(start)
        ...
    else:
        start='' # set start to empty string so the while loop repeats

Here we check that all of the characters in the string `start` are
actually numbers before coercing. This is known as the "Look Before
You Leap" (LBYL) approach. Another approach is to catch the ValueError
exception:

    start = input("\nStart: "))
    try:
        start = int(start)
    except ValueError:
        start = ''
    if start:
        ....

This is known as "Easier to for Ask Forgiveness than
Permission" (EAFP). They both have their advantages. try/excepts tends
to be quicker if few exceptions are called, while an if/else will test
every time, although at this point it's not something you need to
overly concern yourself with. Go with whichever is easiest for you to
understand & extend.



More information about the Python-list mailing list