[Tutor] A range of numbers

Alfred Milgrom fredm at smartypantsco.com
Tue Dec 2 00:25:31 EST 2003


One of the really great aspects of Python is that it is OK to make a mistake!

In fact, one of Python's philosophies is captured in the Python proverb:
"It's better to ask for forgiveness than for permission"

This means: if you think your code will be OK most of the time, but 
occasionally produce an error, go ahead and do it anyway! When an error 
comes up, say sorry :))

The key construct here is "try ... except"

try:
     x, y = mouse_position()

This fragment says: "Try this code. I think it's OK. Don't fall over if it 
is wrong."

But what happens if there is an error (as you reported)?
Then you just tell the program what to do if you were wrong :)), such as:

except:
     # your code for what to do if the "try" code fell over.

You should be aware that the "try ... except" code is very powerful and 
will catch all errors in your "try" code fragment.
For example if your code has a typing error, such as

try:
     x, y = mouse_posiiton()

the "try" segment will fail and you will always default into the except bit.

It is therefore better to specify which error you want to ignore.
You know from the code that didn't work that you get a TypeError if the 
mouse is off the screen, so your code should be

try:
     x, y = mouse_position()
except TypeError:
     # your code for what to do if the "try" code fell over.
     ....

Hope this helps,
Fred Milgrom

At 06:18 PM 1/12/03 -0800, Leung Cris wrote:
>....Dun realy get it.
>
>
>>From: Daniel Ehrenberg <littledanehren at yahoo.com>
>>To: pytutor <tutor at python.org>
>>Subject: Re: [Tutor] A range of numbers
>>Date: Mon, 1 Dec 2003 18:11:52 -0800 (PST)
>>
>>
>>--- Leung Cris <krazie_mu_boi at hotmail.com> wrote:
>> > Forgot to tell you guys, if I don't get my mouse to
>> > the graphics screen, the mouse_position() will
>> > return None instead of a (x,y) . here's the error I
>> > wud get:
>> >
>> > Traceback (most recent call last):
>> >   File "<pyshell#3>", line 1, in ?
>> >     func()
>> >   File "<pyshell#0>", line 6, in func
>> >     x,y = mouse_position()
>> > TypeError: unpack non-sequence
>>
>>Then catch the error. Here's just the unpacking part
>>of the code with the error caught:
>>
>>try:
>>     x, y = mouse_position()
>>except:
>>     x, y = 0, 0
>>
>>Daniel Ehrenberg
>>
>>__________________________________
>>Do you Yahoo!?
>>Free Pop-Up Blocker - Get it now
>>http://companion.yahoo.com/
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>
>_________________________________________________________________
>¦b±zªº¦æ°Ê¸Ë¸m¤W¶Ç°e±µ¦¬ Hotmail ¶l¥ó¡A½Ð²¾¦Ü: 
>http://zh-asiasms.mobile.msn.com
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>





More information about the Tutor mailing list