Avoiding "invalid literal for int()" exception
aine_canby at yahoo.com
aine_canby at yahoo.com
Mon Dec 11 05:22:20 EST 2006
>>> 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:
iVal = -1
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 iVal != -1 and not formatError:
verb.SetImportance(iVal)
break
elif not formatError:
verb.VerbEntered((uniList[0])
else:
print "Enter numbers between 0 and 10..."
Is this the correct way to do this in your opinion? Sorry, I'm totally
new to python and exceptions.
Thanks,
Aine.
More information about the Python-list
mailing list