[Tutor] ASCII Conversion

Blockheads Oi Oi breamoreboy at yahoo.co.uk
Tue Jan 31 07:16:43 CET 2012


On 31/01/2012 05:33, Christian Witts wrote:
> On 2012/01/31 06:50 AM, Michael Lewis wrote:
>> I am trying to do a simple test but am not sure how to get around
>> ASCII conversion of characters. I want to pass in y have the function
>> test to see if y is an integer and print out a value if that integer
>> satisfies the if statement. However, if I pass in a string, it's
>> converted to ASCII and will still satisfy the if statement and print
>> out value. How do I ensure that a string is caught as a ValueError
>> instead of being converted?
>>
>> def TestY(y):
>>     try:
>>         y = int(y)
>>     except ValueError:
>>         pass
>>     if y < -1 or y > 1:
>>         value = 82
>>         print value
>>     else:
>>         pass
>>
>> --
>> Michael J. Lewis
>> mjolewis at gmail.com <mailto:mjolewis at gmail.com>
>> 415.815.7257
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
> If you just want to test if `y` is an integer you can do so with
> `type(y) == int`, and to get the ASCII value of a character you can use
> `ord` like `ord('a') == 97`. And how to avoid your ValueError with a bad
> conversion, do your type checking before hand.
>
> Hope that helps.
> --
>
> Christian Witts
> Python Developer
> //
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

The test of y would not normally be written as it is, comparisons can be 
chained see http://docs.python.org/reference/expressions.html#not-in.
Also Python tends to use EAFP rather than LBYL see 
http://docs.python.org/glossary.html.

-- 
Cheers.

Mark Lawrence.



More information about the Tutor mailing list