473,386 Members | 2,042 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Avoiding "invalid literal for int()" exception

>>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.

Dec 11 '06 #1
8 20251
In <11**********************@j72g2000cwa.googlegroups .com>, aine_canby
wrote:
elif uniList[0].lower() in ("p","pass"):
break
elif int(uniList[0]) in range(0,10):
Replace this line with:

elif uniList[0].isdigit() and 0 <= int(uniList[0]) < 10:
verb.SetImportance(int(uniList[0]))
break
else:
verb.AddNewVerb((uniList[0])
You may want to give `uniList[0]` a name before entering the
``if``/``elif`` construct to avoid accessing the first element over and
over.

Ciao,
Marc 'BlackJack' Rintsch
Dec 11 '06 #2

ai********@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

Dec 11 '06 #3

John Machin skrev:
ai********@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.

Dec 11 '06 #4
At Monday 11/12/2006 07:22, ai********@yahoo.com wrote:
>elif int(uniList[0]) in range(0,10):
Either of these will work to avoid an unneeded conversion:

elif uniList[0] in "0123456789":

elif uniList[0] in string.digits:

elif uniList[0].isdigit():
--
Gabriel Genellina
Softlab SRL

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Dec 11 '06 #5
In <ma***************************************@python. org>, Gabriel
Genellina wrote:
At Monday 11/12/2006 07:22, ai********@yahoo.com wrote:
>>elif int(uniList[0]) in range(0,10):

Either of these will work to avoid an unneeded conversion:

elif uniList[0] in "0123456789":

elif uniList[0] in string.digits:

elif uniList[0].isdigit():
The last does not work. Not only that it accepts numbers greater than 9
because it checks if the whole string consists of digits, it also accepts
u'²₂' and other unicode digits.

Ciao,
Marc 'BlackJack' Rintsch
Dec 12 '06 #6
Marc 'BlackJack' Rintsch wrote:
In <ma***************************************@python. org>, Gabriel
Genellina wrote:
>At Monday 11/12/2006 07:22, ai********@yahoo.com wrote:
>>>elif int(uniList[0]) in range(0,10):

Either of these will work to avoid an unneeded conversion:

elif uniList[0] in "0123456789":

elif uniList[0] in string.digits:

elif uniList[0].isdigit():

The last does not work. Not only that it accepts numbers greater than 9
because it checks if the whole string consists of digits, it also accepts
u'²?' and other unicode digits.
By the way, if you require an implicit 0 <= int(s) < 10 check, none of the
above work with the newer Pythons:
>>s = "23"
s in "0123456789"
True
>>s in set("0123456789")
False

Peter
Dec 12 '06 #7
Marc 'BlackJack' Rintsch ha escrito:
In <ma***************************************@python. org>, Gabriel
Genellina wrote:
elif uniList[0].isdigit():

The last does not work. Not only that it accepts numbers greater than 9
because it checks if the whole string consists of digits, it also accepts
u'²₂' and other unicode digits.
Oh, I didn't know that last part! Thanks.
I get a bit confused by the [0], thinking it was checking a single
character.

--
Gabriel Genellina

Dec 12 '06 #8
Gabriel Genellina wrote:
>>elif uniList[0].isdigit():
>The last does not work. Not only that it accepts numbers greater than 9
because it checks if the whole string consists of digits, it also accepts
u'²₂' and other unicode digits.

Oh, I didn't know that last part! Thanks.
I get a bit confused by the [0], thinking it was checking a single
character.
if you really want to use isdigit(), writing

uniList[0].encode("ascii", "ignore").isdigit()

should solve the unicode issue, I think.

</F>

Dec 12 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: CoolPint | last post by:
Standard exception classes in C++ have what() which returns const char * and they have constructors accepting string. Where is that string created and when is the string destroyed? In the...
21
by: Stephan | last post by:
why does the following code not work???? after compiling and running it will just say killed after all my memory filled up any suggestions? #include <iostream> using namespace std; void...
16
by: Don Starr | last post by:
When applied to a string literal, is the sizeof operator supposed to return the size of the string (including nul), or the size of a pointer? For example, assuming a char is 1 byte and a char *...
7
by: al | last post by:
char s = "This string literal"; or char *s= "This string literal"; Both define a string literal. Both suppose to be read-only and not to be modified according to Standard. And both have...
7
by: cmay | last post by:
FxCop complains every time I catch System.Exception. I don't see the value in trying to catch every possible exception type (or even figuring out what exceptions can be caught) by a given block...
9
by: MR | last post by:
I get the following Exception "The data at the root level is invalid. Line 1, position 642" whenever I try to deserialize an incoming SOAP message. The incoming message is formed well and its...
24
by: Earl | last post by:
I have all of my data operations in a separate library, so I'm looking for what might be termed "best practices" on a return type from those classes. For example, let's say I send an update from...
2
by: Lucas | last post by:
Hi, I want to display an exception in a javascript alert and I'm rendering that client code using ClientScript.RegisterStartupScript(GetType(), key,...
1
by: yimma216 | last post by:
Hi I have been trying to get the data display on the datagrid after selecting a customer. With the same connection it populates the selection right. But just do not seem to extract the following...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.