[Tutor] Problem formatting raw_input

Rich Lovely roadierich at googlemail.com
Sat Nov 1 00:55:11 CET 2008


The try: except: clauses allow for someone typing something like  
'spam' when the program expects a number. It stops the program dying  
with an error message.

---
Richard "Roadie Rich" Lovely
Part of the JNP|UK Famille
www.theJNP.com
---
(Sent from my iPod - please allow for any typos: it's a very small  
keyboard)

On 31 Oct 2008, at 18:50, bob gailer <bgailer at gmail.com> wrote:

> Peter Anderson wrote:
>> Dj Gilcrease wrote:
>>> The simple answer is to just use chr(int(inNum))
>>>
>>> though here is how I would do it
>>>
>>> def convert_string_to_int(strInt):
>>>    try:
>>>        return int(strInt)
>>>    except ValueError:
>>>        return 0
>>>
>>> def getNumbers(output):
>>>    inNum = raw_input("Please enter an ASCII number\n(33 - 126,
>>> [Enter] to quit): ")
>>>    ascii_num = convert_string_to_int(inNum)
>>>    if ascii_num >= 33 and ascii_num <=126:
>>>        output.append(chr(ascii_num))
>>>        getNumbers(output)
>
> I would avoid recursion. Save that for recursive algorithms. An  
> ordinary loop is easier to read/maintain and you will not run out of  
> recursion depth. Also give user a meaningful error message.
>
>   while True:
>       inNum = raw_input("Please enter an ASCII number\n(33 - 126,  
> [Enter] to quit): ")
>       if not inNum:
>           break
>       ascii_num = convert_string_to_int(inNum)
>       if ascii_num >= 33 and ascii_num <=126:
>           output.append(chr(ascii_num))
>       else:
>           print "Input must be an integer in range 33..126"
>
>>>
>>> if __name__ == '__main__':
>>>    print "This script converts a sequence of ASCII numbers"
>>>    print "into the string of text that it represents."
>>>    print
>>>    output = []
>>>    getNumbers(output)
>>>    print output
>>>
>>> Dj Gilcrease
>>> OpenRPG Developer
>>> ~~http://www.openrpg.com
>> Dj,
>>
>> Thanks for the suggestions; both work perfectly.  Can I ask a  
>> supplementary question please?
>>
>> In the def convert_string... function why do you include the  
>> "except ValueError: / return 0" clause?
> try: must be followed by except or finally.
>
> -- 
> Bob Gailer
> Chapel Hill NC 919-636-4239
>
> When we take the time to be aware of our feelings and needs we have  
> more satisfying interatctions with others.
>
> Nonviolent Communication provides tools for this awareness.
>
> As a coach and trainer I can assist you in learning this process.
>
> What is YOUR biggest relationship challenge?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list