473,595 Members | 2,623 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 20268
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
2413
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
7249
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
17397
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
4350
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
2326
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
6633
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
2185
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
3741
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
4214
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
7955
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7883
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
8261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8019
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
8251
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...
0
6674
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
3873
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...
0
3911
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1490
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.