try / except not worknig correctly

Brian van den Broek bvande at po-box.mcgill.ca
Sat Mar 12 19:51:01 EST 2005


'@'.join([..join(['fred', 'dixon']), ..join(['gmail', 'com'])]) said
unto the world upon 2005-03-12 19:20:
> the code below will not execute the except section when i enter a
> number.
> what am i missing ?
> 
> #########################################
> .while 1:
> .   print 'Pump Protection ? '
> .   #line 133
> .    try:
> .        myInput = raw_input('A B C D E F G H I J K L ? ')
> .        myInput = string.upper(myInput)
> .        if myInput == 'A':break     #
> .        if myInput == 'B':break     #
> .        if myInput == 'C':break     #
> .        if myInput == 'D':break     #
> .        if myInput == 'E':break     #
> .        if myInput == 'F':break     #
> .        if myInput == 'G':break     #
> .        if myInput == 'H':break     #
> .        if myInput == 'I':break     #
> .        if myInput == 'J':break     #
> .        if myInput == 'K':break     #
> .        if myInput == 'L':break     #
> .    except ValueError:
> .         print "Oops! That was no valid number.  Try again..."
> .         pass
> 
> 
> .'s are to preserve indents.
> fred
> 

Hi fred,

You are missing that raw_input returns a string.

PythonWin 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] 
on win32.
Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) 
- see 'Help/About PythonWin' for further copyright information.
>>> example = raw_input('Give me a number!')
Give me a number!42
>>> type(example)
<type 'str'>
>>>

I am also not sure why you expected a ValueError:

 >>> import string
 >>> a = 42
 >>> string.upper(a)
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "C:\PYTHON24\lib\string.py", line 235, in upper
     return s.upper()
AttributeError: 'int' object has no attribute 'upper'
 >>>


Additionally, string methods are often preferred to the string module:
 >>> b = 'lower'
 >>> b.upper()
'LOWER'
 >>>


You might also want to test

if myInput in ('A', 'B', 'C', 'etc'):
.    break

instead of your chain of if tests.

Best,

Brian vdB





More information about the Python-list mailing list