Avoiding "invalid literal for int()" exception

aine_canby at yahoo.com aine_canby at yahoo.com
Mon Dec 11 06:40:42 EST 2006


John Machin skrev:

> aine_canby at yahoo.com wrote:
> > >>> v = raw_input("Enter: ")
> > Enter: kjjkj
> > >>> int(v)
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in <module>
> > ValueError: invalid literal for int() with base 10: 'kjjkj'
> >
> > In my program I need to be able to enter char strings or int strings on
> > the command line. Then I use an if-elif structure to establish which is
> > which. For example -
> >
> > if uniList[0].lower() in ("e","exit"): # uniList stores a unicode
> > string origionally taken from stdin
> > 	return
> > elif uniList[0].lower() in ("h","help"):
> > 	verb.PrintVerb()
> > elif uniList[0].lower() in ("p","pass"):
> > 	break
> > elif int(uniList[0]) in range(0,10):
> >         verb.SetImportance(int(uniList[0]))
> >         break
> > else:
> >         verb.AddNewVerb((uniList[0])
> >
> > How could I avoid the ValueError exception if uniList[0] == "Åker"? I
> > was thinking of having something like -
> >
> > formatError = False
> > try:
> >       iVal = int(uniList[0])
> >       if iVal not in range range(0,10):
> >             formatError = True
> > catch ValueError:
>
> Perhaps you meant
>     except ValueError:
> :-)
>
>
> >       iVal = -1
> >
>
> Consider using uniList[0].isdigit() -- see
> http://docs.python.org/lib/string-methods.html
> 
> HTH,
> John

Yes, thanks for your help.




More information about the Python-list mailing list