471,330 Members | 1,851 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

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

Try: Except: not catching ValueError (Help)

Eclipse
G'day all

In the code below I am trying to catch an error thrown if i enter any other value than an integer. (I used the string 'six' and the float '1.5')

The error thrown in the command window by the code is:

Traceback (most recent call last):
File "C:\Documents and Settings\Smythville\My Documents\Python\Stuff\Ch4\ex1-6.py", line 59, in <module>
a = int(raw_input("\nTry a number!"))
ValueError: invalid literal for int() with base 10: 'six'

Expand|Select|Wrap|Line Numbers
  1.  
  2. a = int(raw_input("\nTry a number!"))
  3.  
  4. try:
  5.   if a >= 0 and a <= 9:
  6.     print "\nYour number is between or equal to 0 and 9."
  7.   else:
  8.     print "\nYour number is not between or equal to 0 and 9."
  9. except ValueError: 
  10.   print "Could not convert data to an integer."
  11.  
Even though I have specified the ValueError is doesn't catch it.

Any Ideas?

Thanks

Eclipse
Jan 2 '08 #1
1 3017
bvdet
2,851 Expert Mod 2GB
G'day all

In the code below I am trying to catch an error thrown if i enter any other value than an integer. (I used the string 'six' and the float '1.5')

The error thrown in the command window by the code is:

Traceback (most recent call last):
File "C:\Documents and Settings\Smythville\My Documents\Python\Stuff\Ch4\ex1-6.py", line 59, in <module>
a = int(raw_input("\nTry a number!"))
ValueError: invalid literal for int() with base 10: 'six'

Expand|Select|Wrap|Line Numbers
  1.  
  2. a = int(raw_input("\nTry a number!"))
  3.  
  4. try:
  5.   if a >= 0 and a <= 9:
  6.     print "\nYour number is between or equal to 0 and 9."
  7.   else:
  8.     print "\nYour number is not between or equal to 0 and 9."
  9. except ValueError: 
  10.   print "Could not convert data to an integer."
  11.  
Even though I have specified the ValueError is doesn't catch it.

Any Ideas?

Thanks

Eclipse
Move the first line of code inside the try block.
Jan 2 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

39 posts views Thread by Erlend Fuglum | last post: by
2 posts views Thread by Mike Hoy | last post: by
7 posts views Thread by Derek Schuff | last post: by
12 posts views Thread by Carl J. Van Arsdall | last post: by
13 posts views Thread by John Salerno | last post: by
35 posts views Thread by Arnaud Delobelle | last post: by
7 posts views Thread by oscartheduck | last post: by
reply views Thread by rosydwin | last post: by

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.