473,799 Members | 3,161 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Avoiding "invalid literal for int()" exception

>>v = raw_input("Ente r: ")
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.SetImporta nce(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.SetImporta nce(iVal)
break
elif not formatError:
verb.VerbEntere d((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 20281
In <11************ **********@j72g 2000cwa.googleg roups.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.SetImporta nce(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********@yaho o.com wrote:
>v = raw_input("Ente r: ")
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.SetImporta nce(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********@yaho o.com wrote:
>>v = raw_input("Ente r: ")
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.SetImporta nce(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********@yaho o.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************ *************** ************@py thon.org>, Gabriel
Genellina wrote:
At Monday 11/12/2006 07:22, ai********@yaho o.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************ *************** ************@py thon.org>, Gabriel
Genellina wrote:
>At Monday 11/12/2006 07:22, ai********@yaho o.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************ *************** ************@py thon.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").isdig it()

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
2424
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 function below, e is a local object so when the function terminates, the internal string should be gone too, isn't it?
21
7288
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 out_of_mem() {
16
17507
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 * is 4 bytes, should the following yield 4, 5, of something else? (And, if something else, what determines the result?) char x = "abcd"; printf( "%d\n", sizeof( x ) ); -Don
7
4366
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 type of "const char *". Right? But why does the compiler I am using allow s to be modified, instead of generating compile error?
7
2342
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 of code, when System.Exception seems to get the job done for me. My application is an ASP.Net intranet site. When I catch an exception, I log the stack trace and deal with it, normally by displaying an error
9
6654
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 length is 642 bytes ( I have appended it to the end of this message). I suspect that the reason may have something to do with an incorrect declaration of which class to de-serialize to. In the attached code I substituted @@@@@@@ in the code below with...
24
2199
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 the UI layer to a method in a library class that calls the stored procedure. Best to return a boolean indicating success/failure, return a string with the exception message, or just return the entire exception?
2
3748
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, string.Format(@"<script>alert('ERROR:\r\n\r\n{0}');</script>", ex.ToString())); The problem is that ex.ToString() contains escape characters that not
1
4225
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 SQL. The litABC is to check the flow of control. There is no syntax error but in the debug menu, I got A first chance exception of type 'System.Data.Odbc.OdbcException' occurred in System. Where did I do wrong?
0
9541
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10251
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10228
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10027
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7565
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4141
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.