[Tutor] ASCII Conversion
Joel Goldstick
joel.goldstick at gmail.com
Tue Jan 31 21:28:08 CET 2012
On Tue, Jan 31, 2012 at 4:06 AM, Russel Winder <russel at russel.org.uk> wrote:
> On Tue, 2012-01-31 at 07:33 +0200, Christian Witts wrote:
>> [...]o 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.
>
> isinstance ( y , int )
>
> preferred?
>
> Violates EAFP obviously but...
>
> --
> Russel.
> =============================================================================
> Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net
> 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at russel.org.uk
> London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
I took a slightly different approach as shown:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def test(y):
... try:
... if abs(y) > 1:
... print 83
... except ValueError:
... pass
...
>>> test(.5)
>>> test(5)
83
>>> test('bob')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in test
TypeError: bad operand type for abs(): 'str'
>>> int('bob')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'bob'
>>>
First, I like abs(y) > 1 rather than the double test which is
confusing for me to read.
This fails if y isn't a number, but it fails with ValueError instead
of TypeError.
Since I was just playing around, I have printed the complete session.
To make my code play right, I would substitue the ValueError where I
have TypeError and I think I have what you wanted.
Oh, I used 83 instead of 82.. No idea why I did that
--
Joel Goldstick
More information about the Tutor
mailing list