Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread Marc Tompkins
On Tue, May 21, 2013 at 11:25 PM, Bod Soutar  wrote:

> On 22 May 2013 07:20, Jim Mooney  wrote:
> >> Keep the try block small. For example if it's for a call to
> >> open(filename, "r") the only possible errors (assuming correct syntax)
> >> are NameError for using an undefined variable and IOError for
> >> specifying a file which doesnt exist.
> >
> > Thanks. Since I'm new at this the error lists I saw just had the bald
> > names, which didn't tell me much. But I found a concise and basic
> > explanation of each error at
> > http://python.about.com/od/pythonstandardlibrary/a/lib_exceptions.htm
> >
> > Although it's still a bit circular at my level. I won't be sure what
> > errors to raise until I see enough errors, but that will come with
> > experience, I guess. Now I just have to figure how to print the list
> > out without the ads ;')
> >
> > Jim
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
> One thing I tend to do is fire up the interpreter and deliberately
> write something that should fail, then I can see what error is raised.
> For example, when I suggested the open() test, I fired up the
> interpreter and tried
>
> >>> open(dave, "r")
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'dave' is not defined
>
> >>> open("dave2", "r")
> Traceback (most recent call last):
>   File "", line 1, in 
> IOError: [Errno 2] No such file or directory: 'dave2'
>

I would just like to contribute my $.02 worth here and say: be VERY
conservative about assuming that you know what the error was/what caused
it.  As a user, and as support for users, nothing irritates me more than a
program that lies to me (unintentionally, of course) about what's wrong.
Case in point: back in the 80s and early 90s, "out of memory" errors were
extremely common - not necessarily because memory was actually scarce (it
WAS, but we knew how to deal with that) but because that was the default
error code if nothing else matched.  The actual error was sometimes "file
not found", or "printer not plugged in", or something else equally
unrelated to an actual shortage of memory - but because the programmer had
1) not foreseen the particular problem and 2) put in a catch-all that
assumed that "all errors not otherwise specified" were "out of memory",
troubleshooting was much harder than it should have been.

In short: if you're going to take the "catch all errors" approach (instead
of simply predicting what the most common errors might be), always let the
default be either to display the error and a traceback (in a dialog box,
for example) or to actually let the program crash and display the error on
stdout.  If you try to be too clever, your users will end up hating you for
it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] still nosing around

2013-05-22 Thread Albert-Jan Roskam


 


> Personally, I recommend you start with doctests rather than nose or unittest. 


Doctests can also be run using nose, maybe that's also an idea? Nose does 
doctest, unittest, and its own tests. By default, test files need to have a 
prefix "test_". Unless you specify this either as a commanline switch or in the 
.cfg file, nose won't do doctests. 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] trying to split or rpartition the contents of a list

2013-05-22 Thread Stuart Tozer
Hi everyone.

I'm stuck on a problem while developing a small tool for Maya. Basically, I
have a folder with some filenames in it which have been returned by
os.listdir().
These filenames look something like...


apple_d.jpg
apple_si.jpg
apple_sg.jpg
box_d.jpg
box_si.jpg
pumpkin_d.jpg


Right now, I'm using os.listdir to get the filenames, and then each
filename becomes a selectable option in an option menu in maya. The code
is...

objects = os.listdir(dir)





for object in objects:
cmds.menuItem(label = object, parent = "objectMenu")



My problem is that I don't want duplicates of the same object in the menu
and I also want to truncate everything past and including the underscore.
So for eg, if my filenames are the same as the example above, I want to
change the list so I have this instead...

apple
box
pumpkin


I have tried splitting the filenames, but so far haven't had any luck.

for object in objects:
sorted(set(object.split('_', 1)[0]))
cmds.menuItem(label = object, parent = "objectMenu")



Also, I tried .rpartition but also no luck. I'm very new to python and this
has me stumped.
Any suggestions would be most welcome! ;)

Cheers,
S Tozer




-- 
http://stutozer.elementfx.com/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] challenge-chapter 2

2013-05-22 Thread Peter Otten
Andrew Triplett wrote:

> I am on chapter two for Python Programming working on the challenges and
> the question is:
> 
> 1. Create a list of legal and illegal variable names. Describe why each is
> either legal or illegal. Next, create a list of "good" and "bad" legal
> variable names. Describe why each is either a good or bad choice for a
> variable name.
> 
> Can you help me solve this problem?

i
n
foo
1timepad
with
__
_name
__name
row1
row2
row3
question
length
x
bottles
number_of_bottles
number_of_bottles_of_beer_on_the_wall
seperate_concerns
next_KindOfQuestion
it's_about_time
Animal
animal
ANIMAL
HttpServer
HTTPServer
bin2hex
bin_to_hex
childs
intNumber
strValue

So here's your lists, but they got totally mixed up. Also, while it's easy 
to separate the legal from the illegal names (by typing them into the 
interpreter) the distinction between good and bad is not so clear-cut.
You really have to think about it and form an opinion. Write it down in a 
sentence or two and post it here.

Hint: Often a name may even be good or bad depending on the context.
For example

for x, y in points:
r = math.sqrt(x*x + y*y)
print x, y, "-->", r

Here x is a fine name because if follows a well-known mathematical 
convention...

with open(datafile, "rb") as f:
x = pickle.load(f)

...whereas this x leaves you totally clueless about what x could contain.


Another hint: One criterium to decide whether a name is "good" is its 
compliance with PEP 8 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] trying to split or rpartition the contents of a list

2013-05-22 Thread Amit Saha
Hello,

On Wed, May 22, 2013 at 5:49 PM, Stuart Tozer  wrote:
> Hi everyone.
>
> I'm stuck on a problem while developing a small tool for Maya. Basically, I
> have a folder with some filenames in it which have been returned by
> os.listdir(). These filenames look something like...
>
>
> apple_d.jpg
> apple_si.jpg
> apple_sg.jpg
> box_d.jpg
> box_si.jpg
> pumpkin_d.jpg
>
>
> Right now, I'm using os.listdir to get the filenames, and then each filename
> becomes a selectable option in an option menu in maya. The code is...
>
> objects = os.listdir(dir)
>
>
>
>
>
> for object in objects:
> cmds.menuItem(label = object, parent = "objectMenu")
>
>
>
> My problem is that I don't want duplicates of the same object in the menu
> and I also want to truncate everything past and including the underscore. So
> for eg, if my filenames are the same as the example above, I want to change
> the list so I have this instead...
>
> apple
> box
> pumpkin
>
>
> I have tried splitting the filenames, but so far haven't had any luck.
>
> for object in objects:
> sorted(set(object.split('_', 1)[0]))
> cmds.menuItem(label = object, parent = "objectMenu")

You are almost there.

Something like this should work:

>>> labels = ['apple_d.jpg','apple_si.jpg','apple_sg.jpg','box_si.jpg']

Now, create a list of only the names (upto _):

>>> labels_processed=[ ]
>>> for label in labels:
... labels_processed.append(label.split('_')[0])
...

Remove the duplicates:

>>> set(labels_processed)
set(['box', 'apple'])

If you have any doubts about this, please ask.

Best,
Amit.



--
http://echorand.me
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] trying to split or rpartition the contents of a list

2013-05-22 Thread Albert-Jan Roskam
>

>forobjectinobjects:sorted(set(object.split('_',1)[0]))cmds.menuItem(label 
>=object,parent ="objectMenu")


"sorted" returns the sorted list but you don't assign anything to it. You can 
either assign it to a variable, or use the .sort method instead. Also, you 
don't need to specify the maxsplit argument (1) in .split. Also, you used 
'object' as a loop index but this is a reserved word. Why not use the more 
descriptive "for filename in filenames"?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] trying to split or rpartition the contents of a list

2013-05-22 Thread Stuart Tozer
Thanks very much guys- I'll get back to this when I have a spare moment and
let you know how I get on.

Cheers,
Stu



On Wed, May 22, 2013 at 11:06 AM, Albert-Jan Roskam  wrote:

> >
>
> >forobjectinobjects:sorted(set(object.split('_',1)[0]))cmds.menuItem(label
> =object,parent ="objectMenu")
>
>
> "sorted" returns the sorted list but you don't assign anything to it. You
> can either assign it to a variable, or use the .sort method instead. Also,
> you don't need to specify the maxsplit argument (1) in .split. Also, you
> used 'object' as a loop index but this is a reserved word. Why not use the
> more descriptive "for filename in filenames"?
>



-- 
http://stutozer.elementfx.com/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] challenge-chapter 2

2013-05-22 Thread Matthew Ngaha
On Wed, May 22, 2013 at 6:02 AM, Andrew Triplett  wrote:
> I am on chapter two for Python Programming working on the challenges and the
> question is:
>
> 1. Create a list of legal and illegal variable names. Describe why each is
> either legal or illegal. Next, create a list of "good" and "bad" legal
> variable names. Describe why each is either a good or bad choice for a
> variable name.
>

The title is a bit ambigious. Just incase anyone likes the sound of
the challenge, the book is:
Python Programming For The Absolute Beginner
i also used it and would recommend it to anyone trying to learn Python
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 111, Issue 72

2013-05-22 Thread eryksun
On Wed, May 22, 2013 at 12:26 AM, Jim Mooney  wrote:
>
> Actually, I did notice that tests were zero, but the book I am using
> does not mention needing the word 'test' as part of the regex. There
> is only so much time in a day and so many books I can buy (and not all
> comprehensive, apparently.)

Please don't reply to digests. Each message has a Message-ID, and
replies have an IN-REPLY-TO field that references the ID of the
previous message in the thread. By replying to the digest your message
has no meaningful Subject, and even if you change the Subject field,
it still won't be threaded properly. See for yourself:

http://mail.python.org/pipermail/tutor/2013-May/thread.html#95572
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] still nosing around

2013-05-22 Thread Walter Prins
Hi,

On 22 May 2013 05:26, Jim Mooney  wrote:

> But that brings up a point. Does this mean that if I have to test a
> module with a lot of subroutines I have to rename every subroutine
> with 'test' appended?
>

Some quick comments for what it's worth: (One of) the points about nose is
to make lessen the overhead needed to write tests.  With unittest, you have
to create a subclass of unittest.Testcase in order to identify and package
tests for the test framework, and  manually organise them into suites.
 This is fine, but slightly burdensome if all you want is to write a
function or functions that tests another function or functions (maybe
working still in just one single file at that point, as it were, on a
single function or so.)

Nose allows you to do this, e.g. just start writing tests with as little
friction/resistance as possible.  But there's a question:  How is the test
runner now supposed to "know" whether an arbitrary function in a module is
in fact a test?  With unittest, the test framework "knows" (get it) by the
fact that tests are descended from a common base class.  But with an
arbitrary function, how should the test framework know?

So to answer your question: In short, yes, you have to let nose know
whether a given piece of code is a test.  Either include the word "test" in
the function name either prefixed or postfixed as "_test" as you asked Or
you can do it like unittest requires, e.g. create a test class descended
from unittest.Testcase, in which case your method names then don't matter
IIRC.  You may have read this already, but the relevant documentation page:
https://nose.readthedocs.org/en/latest/writing_tests.html

Aside, doctest answers/approaches this same question by reading IIRC
docstring entries for classes, methods or modules (?) and assumes that text
that looks like  python interpreter styled input/output sequences defines
test input/output sequences.

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] still nosing around

2013-05-22 Thread Dave Angel


On 22 May 2013 05:26, Jim Mooney  wrote:

> But that brings up a point. Does this mean that if I have to test a
> module with a lot of subroutines I have to rename every subroutine
> with 'test' appended?
>

No, you don't rename the existing functions.  But the testing functions 
need to be identifiable, in one of several ways.



--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread Steven D'Aprano

On 22/05/13 15:46, Jim Mooney wrote:

I'm looking at Try..Except

Try:
  
Except SomethingError as err:
 

The list of error statements is huge. How do I know which error
statement to put in place of SomethingError (or multiple errors for
that matter)? Or is it best to just leave SomethingError blank until I
know more?




For playing around at the interactive interpreter, leaving the except clause 
blank is fine.

try:
something()
except:
pass


But don't do this in real code! In real code, the rules you should apply are:


1) never hide programming errors by catching exceptions;

2) errors should only be caught if you can recover from them;

3) your job as a programmer is *not* to stop your program from raising an 
error, but to make it behave correctly -- sometimes an error is the right thing 
to do;

4) catch the fewest possible errors that make sense;

5) nearly always, "the fewest" will mean *zero* -- 99% of your code should not 
be inside a try...except block;

6) you should put the least amount of code as possible inside each try block -- as a 
general rule, that doesn't just mean "one line of code", but *one operation*.



Unfortunately there is no hard rule about what exceptions Python will raise. 
Some things are obvious: if you mistype a name, you'll probably get a 
NameError. Some things are documented: if you look up an item in a dict, and it 
is not there, you will get KeyError. Some things are not. E.g. there's pretty 
much no limit to the exceptions you *might* (but probably never will!) get from 
some of the more complex modules.

In general, once I have decided that I need a try...except block around a 
certain operation, I look up what exceptions it is documented to produce (if 
any!). Then I decide, if such-and-such an exception occurs, can I recover from 
it? If not, I don't catch it. If so, then I do. Then, I wait to see if the 
operation produces some other undocumented exception. If so, then I repeat the 
process.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread Steven D'Aprano

On 22/05/13 16:20, Jim Mooney wrote:

Keep the try block small. For example if it's for a call to
open(filename, "r") the only possible errors (assuming correct syntax)
are NameError for using an undefined variable and IOError for
specifying a file which doesnt exist.



Jim, I don't know who you are replying to here. You have quoted somebody, but 
not included an attribution. Whoever it was that replied to you, I don't seem 
to have their email (maybe they sent it direct to you, not to the list?) so I 
have no idea who it was.

However, let me say that under normal circumstances, you should not catch 
NameError. A NameError is almost always a programming error: you have made a 
typo, or tried using a variable that doesn't exist. You need to see that error, 
so you can fix it, not just hide it with a try...except.

A very important quote from Chris Smith:

"I find it amusing when novice programmers believe their main job is preventing 
programs from crashing. ... More experienced programmers realize that correct code is 
great, code that crashes could use improvement, but incorrect code that doesn't crash is 
a horrible nightmare."

In the specific case of the open command, there are many other errors that can 
occur:

IOError, if the file doesn't exist, or is unreadable, or if you do not have 
read permission, or any one of a number of rarer file-system errors;

TypeError, if the file name contains an ASCII NULL character, or if you pass 
something other than a file name;

TypeError again, if you pass too few, or too many, arguments;

ValueError, if you provide an illegal mode argument (e.g. 'x' instead of 'r' or 
'w');

to mention only a few. But nearly all of them are programming errors, and 
should not be caught, they should be fixed. E.g. if you get a NameError, *fix 
the typo*. If you get ValueError, *use a legal mode*. And so forth. IOError is 
probably the only one you might legitimately want to catch, and even then only 
if you can recover from the error.


--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread boB Stepp
On Wed, May 22, 2013 at 7:50 AM, Steven D'Aprano  wrote:
> On 22/05/13 15:46, Jim Mooney wrote:
>>

[...]

>
> But don't do this in real code! In real code, the rules you should apply
> are:
>
>
> 1) never hide programming errors by catching exceptions;
>
> 2) errors should only be caught if you can recover from them;
>

I have not made it to the point of catching errors. I am still at the
stage of doing my best to prevent them from occurring. However, I try
to follow all of the posts as best I can and I am not sure I
understand what you mean here. You seem to be saying that there may be
errors that you cannot eliminate, but also cannot do anything about if
they happen to occur. Am I interpreting this correctly? Please
clarify.

> 3) your job as a programmer is *not* to stop your program from raising an
> error, but to make it behave correctly -- sometimes an error is the right
> thing to do;
>

Also, can you clarify this point as well? When would you want your
program to crash?

> 4) catch the fewest possible errors that make sense;
>
> 5) nearly always, "the fewest" will mean *zero* -- 99% of your code should
> not be inside a try...except block;
>
> 6) you should put the least amount of code as possible inside each try block
> -- as a general rule, that doesn't just mean "one line of code", but *one
> operation*.
>

Here by "one operation" do you mean the most efficient means to deal
with that particular error condition?

[...]

> In general, once I have decided that I need a try...except block around a
> certain operation, I look up what exceptions it is documented to produce (if
> any!). Then I decide, if such-and-such an exception occurs, can I recover
> from it? If not, I don't catch it. If so, then I do. Then, I wait to see if
> the operation produces some other undocumented exception. If so, then I
> repeat the process.
>
Maybe I have been totally misunderstanding your comments. Is what you
are saying above referring strictly to while you are still debugging
the program? Or do the above comments that I asked for clarification
refer to the finished product?

Thanks!
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread boB Stepp
On Wed, May 22, 2013 at 8:07 AM, Steven D'Aprano  wrote:
> On 22/05/13 16:20, Jim Mooney wrote:
>>>

[...}

> A very important quote from Chris Smith:
>
> "I find it amusing when novice programmers believe their main job is
> preventing programs from crashing. ... More experienced programmers realize
> that correct code is great, code that crashes could use improvement, but
> incorrect code that doesn't crash is a horrible nightmare."
>

Being a novice programmer, I am interpreting this to mean that a) I
complete a program. b) I believe it to be correct and bug-free. c) I
should make sure I do NOT try to catch errors just to keep the program
running from things I failed to anticipate (Probably from being a
novice programmer!). So the conclusion I am drawing is that I WANT my
program to crash if something I did not anticipate/plan for happens.
Am I understanding this correctly?

boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread Steven D'Aprano

On 22/05/13 23:31, boB Stepp wrote:

On Wed, May 22, 2013 at 7:50 AM, Steven D'Aprano  wrote:

On 22/05/13 15:46, Jim Mooney wrote:




[...]



But don't do this in real code! In real code, the rules you should apply
are:


1) never hide programming errors by catching exceptions;

2) errors should only be caught if you can recover from them;



I have not made it to the point of catching errors. I am still at the
stage of doing my best to prevent them from occurring. However, I try
to follow all of the posts as best I can and I am not sure I
understand what you mean here. You seem to be saying that there may be
errors that you cannot eliminate, but also cannot do anything about if
they happen to occur. Am I interpreting this correctly? Please
clarify.



Correct. Some errors can be recovered from, e.g. if a website is not available, you can 
wait a few seconds and try again; if a file cannot be read, you can ask the user for a 
different file name. Some errors cannot reasonably be recovered from. If you ask the user 
for a number between 1 and 10, and they enter "hello", what are you going to do?

If your program is interactive, you can ask them again. But if it is 
non-interactive, you have no choice but to fail gracefully and display an error.

Some errors are *expected* -- users make mistakes, they don't read 
instructions, or misunderstand them, they enter garbage, make typos, etc. Web 
sites and networks go down temporarily, or respond slowly; disks fill up; etc. 
Good programs should deal with them gracefully.

Some errors are *unexpected*, in which case they should be identified as either 
a bug that needs to be fixed, or as an error condition which *should have been 
expected* but wasn't. If you catch every exception in sight, you will never be 
able to identify those unexpected errors and fix them.




3) your job as a programmer is *not* to stop your program from raising an
error, but to make it behave correctly -- sometimes an error is the right
thing to do;



Also, can you clarify this point as well? When would you want your
program to crash?


You don't *want* it to crash, you would rather it exit gracefully. But a crash 
is better than silently doing the wrong thing.

Some years ago there was a very unfortunate incident where a 
computer-controlled medical x-ray irradiated a large number of people with 
fatal doses of radiation. The machine should have halted with an error, but due 
to a combination of bad design, operator error, and programming bugs, instead 
it blasted the poor doomed patients with thousands of times the safe limit of 
radiation.

That's an extreme example, but the same principle applies in general. Your 
program has a job to do. If it cannot do that job correctly, it should own up 
to it rather than do something else. If you tell your program to save your work 
to a file, and the disk is full, what would you rather happen?

- You get an error message, so you can make some space and try again.

- The program silently discards your data, so it is not saved but you don't 
know it.

- The program deletes other files at random until it has freed up enough space 
to save your data.


Pick one.



4) catch the fewest possible errors that make sense;

5) nearly always, "the fewest" will mean *zero* -- 99% of your code should
not be inside a try...except block;

6) you should put the least amount of code as possible inside each try block
-- as a general rule, that doesn't just mean "one line of code", but *one
operation*.



Here by "one operation" do you mean the most efficient means to deal
with that particular error condition?


No. I mean that you should identify (if you can) the smallest thing that can go 
wrong in the way you expect, and deal with it.

For example, suppose you are looking up a key in a dict, and process it in some 
way. If the key is not in the dict, you can deal with it quite easily:


try:
value = my_dict[key]
result = process(value)
except KeyError:
result = something_else()


Looks reasonable, yes?

No. You're guarding too much with the try block. The problem is, there are two 
places where you *might* get a KeyError:

- when you call my_dict[key]

- inside process(value) -- who knows what is happening in there? You have to 
assume that it *could* raise KeyError.

But only the first case can be legitimately handled by the except clause. A 
KeyError in process(value) needs to be treated as a bug, and fixed, not covered 
up. So the above is better written as:

try:
value = my_dict[key]
except KeyError:
result = something_else()
else:
# No exception occurred.
result = process(value)


Now if you get KeyError inside the call to process(), you will see it, and can 
fix it.




In general, once I have decided that I need a try...except block around a
certain operation, I look up what exceptions it is documented to produce (if
any!). Then I decide, if such-and-such an exception occurs, can I recover
from it? If not, I don't catch i

Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread Steven D'Aprano

On 22/05/13 23:37, boB Stepp wrote:

On Wed, May 22, 2013 at 8:07 AM, Steven D'Aprano  wrote:

On 22/05/13 16:20, Jim Mooney wrote:




[...}


A very important quote from Chris Smith:

"I find it amusing when novice programmers believe their main job is
preventing programs from crashing. ... More experienced programmers realize
that correct code is great, code that crashes could use improvement, but
incorrect code that doesn't crash is a horrible nightmare."



Being a novice programmer, I am interpreting this to mean that a) I
complete a program. b) I believe it to be correct and bug-free. c) I
should make sure I do NOT try to catch errors just to keep the program
running from things I failed to anticipate (Probably from being a
novice programmer!). So the conclusion I am drawing is that I WANT my
program to crash if something I did not anticipate/plan for happens.
Am I understanding this correctly?



Yes!


Well, within reason. If you are programming in C, a crash can be a nasty thing 
to deal with. It could cause memory corruption, leading to a Blue Screen of 
Death or equivalent. In the absolute worst case, low-level C or assembly bugs 
can actually cause hardware damage! So you don't want to be writing low-level 
code like that if you can avoid it.

But in a high-level language like Python, exceptions are not to be feared. They 
are perfectly safe, and should be welcomed, since they show you where your code 
needs to be improved.


--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread boB Stepp
Thanks, Steve, for your last two posts. You have made things much
clearer for me.

On Wed, May 22, 2013 at 9:49 AM, Steven D'Aprano  wrote:
> On 22/05/13 23:37, boB Stepp wrote:
>>
>> On Wed, May 22, 2013 at 8:07 AM, Steven D'Aprano 
>> wrote:
>>>

[...]

>>
>> Being a novice programmer, I am interpreting this to mean that a) I
>> complete a program. b) I believe it to be correct and bug-free. c) I
>> should make sure I do NOT try to catch errors just to keep the program
>> running from things I failed to anticipate (Probably from being a
>> novice programmer!). So the conclusion I am drawing is that I WANT my
>> program to crash if something I did not anticipate/plan for happens.
>> Am I understanding this correctly?
>
>
>
> Yes!
>
>
> Well, within reason. If you are programming in C, a crash can be a nasty
> thing to deal with. It could cause memory corruption, leading to a Blue
> Screen of Death or equivalent. In the absolute worst case, low-level C or
> assembly bugs can actually cause hardware damage! So you don't want to be
> writing low-level code like that if you can avoid it.
>

I was not aware that hardware damage could be caused by poor
programming. I am curious; can you give some examples of how this
might occur?

> But in a high-level language like Python, exceptions are not to be feared.
> They are perfectly safe, and should be welcomed, since they show you where
> your code needs to be improved.
>
I would like to ask some general questions here. Problems can arise
from bugs in the operating system, bugs in the programming language(s)
being used, bugs in packages/modules being used, bugs in any third
party packages being used, etc. Also, whenever any one of these things
is updated/upgraded, it can introduce new issues. What strategies can
one use to deal with these possibilities that seem entirely out of the
programmer's control?

boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] challenge-chapter 2

2013-05-22 Thread Evans Anyokwu
Hi Andrew,

I'm sure the exercises at the end of the each chapters are there for you to
attempt. Asking for help here without attempting it is not the best way to
learn.
If however, you've tried something - and it didn't work, by all means ask
for help.

In the mean time show us what you have so far.


Good luck,
Evans


On Wed, May 22, 2013 at 6:02 AM, Andrew Triplett wrote:

> I am on chapter two for Python Programming working on the challenges and
> the question is:
>
> 1. Create a list of legal and illegal variable names. Describe why each is
> either legal or illegal. Next, create a list of "good" and "bad" legal
> variable names. Describe why each is either a good or bad choice for a
> variable name.
>
> Can you help me solve this problem?
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 111, Issue 72

2013-05-22 Thread Jim Mooney
> Please don't reply to digests. Each message has a Message-ID, and
> replies have an IN-REPLY-TO field that references the ID of the
> previous message in the thread. By replying to the digest your message
> has no meaningful Subject, and even if you change the Subject field,
> it still won't be threaded properly. See for yourself:
>
> http://mail.python.org/pipermail/tutor/2013-May/thread.html#95572

So is Reply to All the way to go? For some odd reason Gmail won't
always Reply to All. I'll have to figure out why.

Jim
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 111, Issue 72

2013-05-22 Thread Steven D'Aprano

On 23/05/13 02:13, Jim Mooney wrote:

Please don't reply to digests. Each message has a Message-ID, and
replies have an IN-REPLY-TO field that references the ID of the
previous message in the thread. By replying to the digest your message
has no meaningful Subject, and even if you change the Subject field,
it still won't be threaded properly. See for yourself:

http://mail.python.org/pipermail/tutor/2013-May/thread.html#95572


So is Reply to All the way to go? For some odd reason Gmail won't
always Reply to All. I'll have to figure out why.



If you look at your subscription options:

http://mail.python.org/mailman/listinfo/tutor


you have an option to receive a digest containing many posts in a single email, or to receive 
individual emails. If you are going to reply to messages, please pick individual emails. Then when 
you wish to respond to one email, you hit "Reply To List" (if your email program has that 
option) or "Reply All" (if it doesn't), edit your reply, and send.

If you are planning to be busy or away, and still wish to receive the emails, 
but not reply to them, some people like to go onto digest mode. I've tried 
that, and would not bother.




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] To error statement or not to error statement

2013-05-22 Thread Jim Mooney
>> "I find it amusing when novice programmers believe their main job is
>> preventing programs from crashing. ... More experienced programmers realize
>> that correct code is great, code that crashes could use improvement, but
>> incorrect code that doesn't crash is a horrible nightmare."

Then am I right to assume that rather than put in error statements I
barely understand at this point, the best thing would be to work the
hell out of the program in hope of seeing an error?  Does Python have
something that would do this automatically since I can't see running a
program a hundred times by hand?

Mainly, I'm just learning all this stuff for future reference. I
really doubt I'll need to use nose to find errors in twenty-line
programs. Print, assert, and staring at it for a long time should be
enough for now - and the Wing debugger now and then.

>From the varied replies so far, it sounds to me that debugging is more
of an art than a science. So far the books I've looked at just mention
the basics but don't get into the philosophy of when and how.

Jim
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 111, Issue 72

2013-05-22 Thread eryksun
On Wed, May 22, 2013 at 12:13 PM, Jim Mooney  wrote:
>> Please don't reply to digests. Each message has a Message-ID, and
>> replies have an IN-REPLY-TO field that references the ID of the
>> previous message in the thread. By replying to the digest your message
>> has no meaningful Subject, and even if you change the Subject field,
>> it still won't be threaded properly. See for yourself:
>>
>> http://mail.python.org/pipermail/tutor/2013-May/thread.html#95572
>
> So is Reply to All the way to go? For some odd reason Gmail won't
> always Reply to All. I'll have to figure out why.

You can configure Gmail to default to reply all in the general
settings. Of course that's of no use if you're replying to a digest,
so switch to receiving individual messages. Receiving the list as a
digest is unnecessary with Gmail. Just create a label for the list,
and use a filter to automatically label and archive messages from the
list out of your inbox.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread boB Stepp
On Wed, May 22, 2013 at 9:45 AM, Steven D'Aprano  wrote:
> On 22/05/13 23:31, boB Stepp wrote:
>>
>> On Wed, May 22, 2013 at 7:50 AM, Steven D'Aprano 
>> wrote:

[...]

>>> 3) your job as a programmer is *not* to stop your program from raising an
>>> error, but to make it behave correctly -- sometimes an error is the right
>>> thing to do;
>>>
>>
>> Also, can you clarify this point as well? When would you want your
>> program to crash?
>
>
> You don't *want* it to crash, you would rather it exit gracefully. But a
> crash is better than silently doing the wrong thing.
>

Would you define "exiting gracefully"? It appears you mean a
controlled (by the programmer's code) exit that gives a meaningful (to
the user or the programmer?) error message instead of in an
uncontrolled manner where the only available information would be
whatever the OS generates.

> Some years ago there was a very unfortunate incident where a
> computer-controlled medical x-ray irradiated a large number of people with
> fatal doses of radiation. The machine should have halted with an error, but
> due to a combination of bad design, operator error, and programming bugs,
> instead it blasted the poor doomed patients with thousands of times the safe
> limit of radiation.
>

Thanks for the example! Unfortunately these devastating errors
continue. The New York Times has reported on some radiation therapy
incidents in the past few years, some of which were caused by
programming errors (along with the usual errors by the people using
the software).

> That's an extreme example, but the same principle applies in general. Your
> program has a job to do. If it cannot do that job correctly, it should own
> up to it rather than do something else. If you tell your program to save
> your work to a file, and the disk is full, what would you rather happen?
>

I like very much how you put this. Integrity in programming!

> - You get an error message, so you can make some space and try again.
>
> - The program silently discards your data, so it is not saved but you don't
> know it.
>
> - The program deletes other files at random until it has freed up enough
> space to save your data.
>
>
> Pick one.
>

I guess I'll pick the first alternative. However, this brings to mind
my biggest gripe as a user of software, particularly here at work
where the programmer obviously has no medical background: cryptic
error messages that might be meaningful to the programmer, but are
totally unhelpful to me, the user, who has to figure out what to do
next.

[...]

Thanks for the clarifications!

boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread Steven D'Aprano

On 23/05/13 02:09, boB Stepp wrote:


I was not aware that hardware damage could be caused by poor
programming. I am curious; can you give some examples of how this
might occur?


Does your computer have a DVD drive? Or Blu-Ray? Is it region-locked? Some region-locked 
drives let you change the region up to a maximum of (say) 3 times. A malicious or unlucky 
program may "accidentally" change the region 3 times, then you are locked for 
good. If you're locked in the wrong region, the drive might as well be dead.

Some DVD burners are capable of operating at speeds faster than low-quality 
discs can stand. DVDs have been known to shatter inside the drive, destroying 
both the disk and the drive. If a program runs the DVD at excessively high 
speed, not only do the mechanical parts wear faster, but cheap disks could 
shatter.

(I never shattered a DVD or CD, but I went through about 50 blank CDs, back when they 
were about two dollars each, making "coasters" from them because I was trying 
to burn data to them faster than the disc was capable of dealing with. I will never 
forgot the moment I realised why four out of five of my burns were failing: it was when I 
reached for the SECOND LAST DISC in the pack.)

You can destroy old CRT monitors by running them at the wrong frequency. I 
don't think LCD monitors are subject to that particular flaw, but they may have 
their own flaws.

Many computer components are running firmware from flash memory, and you can update the 
firmware. If you update it with garbage instead of code, your device will be bricked. 
Flash memory can only be written to so many times. If your code "accidentally" 
writes to flash memory, over and over again, eventually it will get corrupted or die, and 
your device is bricked.

The Stuxnet computer virus was designed to physically break centrifuges.

http://arstechnica.com/tech-policy/2011/07/how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history/

See also:

http://en.wikipedia.org/wiki/Killer_poke
http://en.wikipedia.org/wiki/Halt_and_Catch_Fire
http://superuser.com/questions/313850/can-some-software-physically-damage-hardware

and of course, always mount a scratch monkey before performing hardware tests:

http://edp.org/monkey.htm


[...]

I would like to ask some general questions here.


I'd love to answer, but it's past 3am here and I must get some sleep 
eventually, so I'll try to return to this topic tomorrow.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread Marc Tompkins
On Wed, May 22, 2013 at 9:50 AM, boB Stepp  wrote:

> I guess I'll pick the first alternative. However, this brings to mind
> my biggest gripe as a user of software, particularly here at work
> where the programmer obviously has no medical background: cryptic
> error messages that might be meaningful to the programmer, but are
> totally unhelpful to me, the user, who has to figure out what to do
> next.
>

I agree with you a LOT more strongly in the case of compiled languages,
where the error dump amounts to a memory location and a blob of
hexadecimal.  When that happens, nobody but the original programmer (or
software company) is likely to find out the cause, and even then not
without a symbolic debugger.  But in Python, the error messages/tracebacks
are fairly self-explanatory (to someone familiar with Python) and even
include the actual line number where the error occurred.  It's true that
the average end-user won't be able to fix it, but the pool of potential
help is actually quite wide.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Available characters

2013-05-22 Thread Citizen Kant
Does anybody know if there's a Python method that gives or stores the
complete list of ascii characters or unicode characters? The list of every
single character available would be perfect.

Thanks.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Available characters

2013-05-22 Thread eryksun
On Wed, May 22, 2013 at 2:14 PM, Citizen Kant  wrote:
> Does anybody know if there's a Python method that gives or stores the
> complete list of ascii characters or unicode characters? The list of every
> single character available would be perfect.

The unicodedata module provides access to the Unicode database that Python uses:

http://docs.python.org/2/library/unicodedata#unicodedata.unidata_version

Here are the versions of the database for Python 2.6.8, 2.7.3, 3.2.3, and 3.3.1:

>>> unicodedata.unidata_version # 2.6.8
'5.1.0'
>>> unicodedata.unidata_version # 2.7.3
'5.2.0'
>>> unicodedata.unidata_version # 3.2.3
'6.0.0'
>>> unicodedata.unidata_version # 3.3.1
'6.1.0'
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread Albert-Jan Roskam


> Subject: Re: [Tutor] try..except - what about that ton of **Error statements?
> 
> On 23/05/13 02:09, boB Stepp wrote:
> 
>>  I was not aware that hardware damage could be caused by poor
>>  programming. I am curious; can you give some examples of how this
>>  might occur?

There used to be a program that would let your harddisk "sing" a melody by 
letting it frantically spin. I always thought this was *not* a good idea, 
though I have never heard of accidents with it. ;-)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Available characters

2013-05-22 Thread Citizen Kant
On Wed, May 22, 2013 at 2:14 PM, Citizen Kant  wrote:
> Does anybody know if there's a Python method that gives or stores the
> complete list of ascii characters or unicode characters? The list of every
> single character available would be perfect.

The unicodedata module provides access to the Unicode database that Python
uses:

http://docs.python.org/2/library/unicodedata#unicodedata.unidata_version

Here are the versions of the database for Python 2.6.8, 2.7.3, 3.2.3, and
3.3.1:

>>> unicodedata.unidata_version # 2.6.8
'5.1.0'
>>> unicodedata.unidata_version # 2.7.3
'5.2.0'
>>> unicodedata.unidata_version # 3.2.3
'6.0.0'
>>> unicodedata.unidata_version # 3.3.1
'6.1.0'


Thanks! This is perfect.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Available characters

2013-05-22 Thread Jim Mooney
> The unicodedata module provides access to the Unicode database that Python
> uses:
>
> http://docs.python.org/2/library/unicodedata#unicodedata.unidata_version

That was really useful for another reason. After I checked and saw it
was in DLLs, I investigated the other Python DLLs  - which had
heretofore seemed mysterious - and found winsound. I happen to be
interested in frequency generation.

Jim
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] keyboard interrupt

2013-05-22 Thread Jim Mooney
I made a simple ear frequency-tester, but I don't want it to go on
forever, so I tried stopping it when I  pressed a key, as below, but
that doesn't work. I did check out keyboard interrupts but they seem
unnecessarily complex just to stop a program. I'm not passing keys. Is
there something simple I'm missing?

import winsound

try:
for freq in range(100,32000,100):
winsound.Beep(freq, 1000)
except KeyboardInterrupt:
pass

-- 
Jim Mooney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keyboard interrupt

2013-05-22 Thread Marc Tompkins
On Wed, May 22, 2013 at 12:47 PM, Jim Mooney wrote:

> I made a simple ear frequency-tester, but I don't want it to go on
> forever, so I tried stopping it when I  pressed a key, as below, but
> that doesn't work. I did check out keyboard interrupts but they seem
> unnecessarily complex just to stop a program. I'm not passing keys. Is
> there something simple I'm missing?
>
> import winsound
>
> try:
> for freq in range(100,32000,100):
> winsound.Beep(freq, 1000)
> except KeyboardInterrupt:
> pass
>
>
I've not used it myself, but I believe the KeyboadInterrupt is only
generated by one _specific_ keypress.  You mentioned that you pressed a key
- did you try Control-C?

http://effbot.org/zone/stupid-exceptions-keyboardinterrupt.htm
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keyboard interrupt

2013-05-22 Thread Jerry Hill
On Wed, May 22, 2013 at 3:47 PM, Jim Mooney wrote:

> I made a simple ear frequency-tester, but I don't want it to go on
> forever, so I tried stopping it when I  pressed a key, as below, but
> that doesn't work. I did check out keyboard interrupts but they seem
> unnecessarily complex just to stop a program. I'm not passing keys. Is
> there something simple I'm missing?
>
> import winsound
>
> try:
> for freq in range(100,32000,100):
> winsound.Beep(freq, 1000)
> except KeyboardInterrupt:
> pass
>
>
The KeyboardInterrupt ​exception is raised when someone presses Ctrl-C.  If
you catch it, and ignore it (which is what your code above is doing), then
pressing Ctrl-C doesn't do anything.  If you just take out the try/except,
then you can hit Ctrl-C and interrupt your program as normal.

-- 
Jerry
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keyboard interrupt

2013-05-22 Thread Jim Mooney
> I've not used it myself, but I believe the KeyboadInterrupt is only
> generated by one _specific_ keypress.  You mentioned that you pressed a key
> - did you try Control-C?

Actually, I did, using Win 7 - and I put exit() in place of pass. I
tried ctrl-c, ctrl-x, esc, and del. Windows doesn't seem to respond to
anything. The prog just goes to the end

Jim
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread Dave Angel

On 05/22/2013 03:03 PM, Albert-Jan Roskam wrote:




Subject: Re: [Tutor] try..except - what about that ton of **Error statements?

On 23/05/13 02:09, boB Stepp wrote:


  I was not aware that hardware damage could be caused by poor
  programming. I am curious; can you give some examples of how this
  might occur?


There used to be a program that would let your harddisk "sing" a melody by 
letting it frantically spin. I always thought this was *not* a good idea, though I have 
never heard of accidents with it. ;-)



I had a young lady working for me that was writing a printer driver, the 
kind that these days would be embedded inside the printer.  I believe it 
was a daisy-wheel printer.  It used a stepper motor which was stepped up 
gradually from zero to full speed and back again.  Anyway, she put a 
breakpoint in the code at the point where the carriage was ramped up, 
and the code stopped, but the carriage kept going, It almost made it 
through the outer wall of the printer - totalled.



--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keyboard interrupt

2013-05-22 Thread Jim Mooney
On 22 May 2013 13:24, Jim Mooney  wrote:
>> I've not used it myself, but I believe the KeyboadInterrupt is only
>> generated by one _specific_ keypress.  You mentioned that you pressed a key
>> - did you try Control-C?
>
> Actually, I did, using Win 7 - and I put exit() in place of pass. I
> tried ctrl-c, ctrl-x, esc, and del. Windows doesn't seem to respond to
> anything. The prog just goes to the end
>
> Jim

Figured it out. Ctrl-C only works in the Windows Command window, not
in an editor.

Jim



-- 
Jim Mooney

"When I got to high school I realized my name would always present
problems." --Dick Hertz
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keyboard interrupt

2013-05-22 Thread Marc Tompkins
On Wed, May 22, 2013 at 1:30 PM, Jim Mooney wrote:

> On 22 May 2013 13:24, Jim Mooney  wrote:
> >> I've not used it myself, but I believe the KeyboadInterrupt is only
> >> generated by one _specific_ keypress.  You mentioned that you pressed a
> key
> >> - did you try Control-C?
> >
> > Actually, I did, using Win 7 - and I put exit() in place of pass. I
> > tried ctrl-c, ctrl-x, esc, and del. Windows doesn't seem to respond to
> > anything. The prog just goes to the end
> >
> > Jim
>
> Figured it out. Ctrl-C only works in the Windows Command window, not
> in an editor.
>

That makes a lot of sense.  And should be added to the list of responses
_next_ time somebody asks "Why shouldn't I run production code in IDLE?"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keyboard interrupt

2013-05-22 Thread eryksun
On Wed, May 22, 2013 at 4:30 PM, Jim Mooney  wrote:
>
> Figured it out. Ctrl-C only works in the Windows Command window, not
> in an editor.

Which IDE?

In IDLE, your code runs in the main thread of a subprocess (unless
IDLE is started with the -n option). A second thread ("SockThread") is
started to communicate with PyShell over a socket. When you press
ctrl-c, PyShell executes an interprocess call to
interrupt_the_server(), which simply executes thread.interrupt_main()
-- i.e. interrupt the main thread with a KeyboardInterrupt:

>>> import thread
>>> thread.interrupt_main()
Traceback (most recent call last):
  File "", line 1, in 
KeyboardInterrupt

Almost certainly your IDE supports interrupting the execution of code.
You just need to configure the key binding. The default binding for
ctrl-c on Windows is to copy the selection to the clipboard.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keyboard interrupt

2013-05-22 Thread Jim Mooney
On 22 May 2013 15:05, eryksun  wrote:
> On Wed, May 22, 2013 at 4:30 PM, Jim Mooney  wrote:
>>
>> Figured it out. Ctrl-C only works in the Windows Command window, not
>> in an editor.
>
> Which IDE?

Wing. But not being able to abort out of a Windows program is a
feature. You don't want to lose seven hours of spreadsheet work
because you forgot and hit ctrl-C. (I just hit Ctrl-C. Nothing, which
is as it should be ;')

Well, it's good to be reminded that an editor does funny stuff as
opposed to command line.

Jim
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Available characters

2013-05-22 Thread Steven D'Aprano

On 23/05/13 04:14, Citizen Kant wrote:

Does anybody know if there's a Python method that gives or stores the
complete list of ascii characters or unicode characters? The list of every
single character available would be perfect.



There are only 127 ASCII characters, so getting a list of them is trivial:

ascii = map(chr, range(128))  # Python 2
ascii = list(map(chr, range(128)))  # Python 3


or if you prefer a string:

ascii = ''.join(map(chr, range(128)))


If you don't like map(), you can use a list comprehension:

[chr(i) for i in range(128)]

The string module already defines some useful subsets of them:

py> import string
py> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~
 \t\n\r\x0b\x0c'


There are 1114111 (hexadecimal 0x10) possible Unicode code-points, but most 
of them are currently unassigned. Of those that are assigned, many of them are 
reserved as non-characters or for special purposes, and even those which are 
assigned, most fonts do not display anything even close to the full range of 
Unicode characters.

If you spend some time on the Unicode web site, you will find lists of 
characters which are defined:

www.unicode.org

but beware, it is relatively heavy going. Wikipedia has a page showing all 
currently assigned characters, but font support is still lousy and many of them 
display as boxes:

http://en.wikipedia.org/wiki/List_of_Unicode_characters

You can generate the entire list yourself, using the same technique as for 
ASCII above:


# Python 2:
unicode = ''.join(map(unichr, xrange(1114112)))

# Python3:
unicode = ''.join(map(chr, range(1114112)))


although it will take a few seconds to generate the entire range. You can then 
get the name for each one using something like this:

import unicodedata
for c in unicode:
try:
print(c, unicodedata.name(c))
except ValueError:
# unassigned, or a reserved non-character
pass


but remember that there are currently almost 100,000 defined characters in 
Unicode, and your terminal will probably not be able to print most of them. 
Expect to see a lot of boxes.




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keyboard interrupt

2013-05-22 Thread Dave Angel

On 05/22/2013 04:11 PM, Jerry Hill wrote:

On Wed, May 22, 2013 at 3:47 PM, Jim Mooney wrote:


I made a simple ear frequency-tester, but I don't want it to go on
forever, so I tried stopping it when I  pressed a key, as below, but
that doesn't work. I did check out keyboard interrupts but they seem
unnecessarily complex just to stop a program. I'm not passing keys. Is
there something simple I'm missing?

import winsound

try:
 for freq in range(100,32000,100):
 winsound.Beep(freq, 1000)
except KeyboardInterrupt:
 pass



The KeyboardInterrupt ​exception is raised when someone presses Ctrl-C.  If
you catch it, and ignore it (which is what your code above is doing), then
pressing Ctrl-C doesn't do anything.  If you just take out the try/except,
then you can hit Ctrl-C and interrupt your program as normal.



What do you mean "doesn't do anything" ?  It certainly terminates the 
loop, which was the intent.  Provided of course that something else 
isn't trapping the Ctrl-C first.







--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keyboard interrupt

2013-05-22 Thread Jim Mooney
> What do you mean "doesn't do anything" ?  It certainly terminates the loop,
> which was the intent.  Provided of course that something else isn't trapping
> the Ctrl-C first.

It doesn't in Windows proper, using Wing 101. It does exit in the
Windows command console. For some reason I forgot ctrl-C is Copy in
windows. I tried Ctrl-X but I was again confusing the old DOS abort
with Windows Cut. I've been enslaved by the GUI ;')

I'm using Wing 101, which doesn't have a feature set for altering that
behavior. It's probably in the professional version. If I scrape up
spare cash I may go for PyCharm or Wing Pro, but I don't need them on
the low end of the learning curve. I'd just waste time fooling with
them.

The program does exit in Idle, although Idle throws up a Tk screen
asking if you want to abort the program, so it's not a clean exit.

Jim
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try..except - what about that ton of **Error statements?

2013-05-22 Thread Steven D'Aprano

On 23/05/13 02:09, boB Stepp wrote:


I would like to ask some general questions here. Problems can arise
from bugs in the operating system, bugs in the programming language(s)
being used, bugs in packages/modules being used, bugs in any third
party packages being used, etc. Also, whenever any one of these things
is updated/upgraded, it can introduce new issues. What strategies can
one use to deal with these possibilities that seem entirely out of the
programmer's control?



They're not really out of your control though. You can always write code
to work around them.

For instance, a long time ago I was using a programming language that had a bug that 
caused the program to crash if you tried to display the string "0^0". If this 
was Python, I might do something like this:

def my_print(astring):
if astring == '0^0':
# Avoid the system bug.
astring = '0 ^ 0'  # Close enough...
print astring


and then make sure I always call my_print instead of print directly.

Sometimes it is sufficient to just avoid triggering the bug. Sometimes you might need use 
a different tool. For instance, in Python, print is not "thread safe" -- if you 
have two different threads trying to print at the same time, their output may interleave.

# Thread 1:
print "Hello world!"

# Thread 2:
print "Goodbye cruel world :-("

# Output might look like this:
HelGoodblo ye crue l worworldld :-(!



Is this a bug in print? No, not really, but it is a limitation, it is not 
designed to be thread safe. So when using threads, you can:

- always make sure only one thread is responsible for doing any printing;

- if you must have multiple threads printing at the same time, use 
sys.stdout.write instead of print, because it is thread-safe.


So working around bugs is, in general, possible, even if sometimes it is hard.

A general technique when programming is to always have a good, solid test 
suite. This will detect any change in behaviour, whether due to your own 
programming errors, on bugs in the language or operating system. What you do is 
as you develop your own code, in parallel you also develop a second program 
that tests as much of your code as you can.

For instance, suppose you have a (trivial) function that doubles a number and 
adds one:

def double_plus_one(x):
return 2*x + 1

So you have a second file open that tests it:


from my_app import *

def test_double_plus_one():
assert double_plus_one(5) == 11
assert double_plus_one(100.25) == 201.5
assert double_plus_one(-0.5) == 0


test_double_plus_one()



(Or you can use a test frame work like unittest or doctest or both.) Now, 
whenever you change something, say you upgrade to a new version of the 
language, or change your code, you run the test file and see what tests start 
failing. Each failed test indicates a bug that needs to be fixed, although it 
doesn't tell you what introduced the bug.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keyboard interrupt

2013-05-22 Thread Dave Angel

On 05/22/2013 09:46 PM, Jim Mooney wrote:

What do you mean "doesn't do anything" ?  It certainly terminates the loop,
which was the intent.  Provided of course that something else isn't trapping
the Ctrl-C first.


It doesn't in Windows proper, using Wing 101.


Then Wing is changing the behavior, trapping the Ctrl-C.  Not sure why 
you would call Wing the "proper Windows".



It does exit in the
Windows command console.


Of course.


For some reason I forgot ctrl-C is Copy in
windows.


Only to programs that have a GUI event loop which happens to trap the 
event.  That's common in Windows, and is required by the CUA standard 
(apparently defunct), but it's not the default behavior of a Windows 
executable.



I tried Ctrl-X but I was again confusing the old DOS abort
with Windows Cut. I've been enslaved by the GUI ;')

I'm using Wing 101, which doesn't have a feature set for altering that
behavior. It's probably in the professional version. If I scrape up
spare cash I may go for PyCharm or Wing Pro, but I don't need them on
the low end of the learning curve. I'd just waste time fooling with
them.

The program does exit in Idle, although Idle throws up a Tk screen
asking if you want to abort the program, so it's not a clean exit.

Jim





--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] keyboard interrupt

2013-05-22 Thread eryksun
On Wed, May 22, 2013 at 8:56 PM, Jim Mooney  wrote:
> On 22 May 2013 15:05, eryksun  wrote:
>> On Wed, May 22, 2013 at 4:30 PM, Jim Mooney  wrote:
>>>
>>> Figured it out. Ctrl-C only works in the Windows Command window, not
>>> in an editor.
>>
>> Which IDE?
>
> Wing. But not being able to abort out of a Windows program is a
> feature. You don't want to lose seven hours of spreadsheet work
> because you forgot and hit ctrl-C. (I just hit Ctrl-C. Nothing, which
> is as it should be ;')
>
> Well, it's good to be reminded that an editor does funny stuff as
> opposed to command line.

Apparently Wing isn't as savvy as IDLE when it comes to communicating
with the subprocess. I've only searched for about a minute, but
apparently the way this works in Wing is to "Restart Shell":

http://stackoverflow.com/a/10360503/205580
http://www.wingware.com/doc/debug/interactive-python-shell

This kills the suprocess and starts a new interpreter. Crude, but it
should get the job done.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor