Teaching python (programming) to children
Duncan Booth
duncan at NOSPAMrcp.co.uk
Fri Nov 9 05:03:09 EST 2001
hungjunglu at yahoo.com (Hung Jung Lu) wrote in
news:8ef9bea6.0111060838.24996280 at posting.google.com:
> How soon does a beginner run into the following problem? (see also the
> "How much is set in stone?" thread)
>
> #------------------
> flag = 0
>
> def f(x):
> flag = 1
> return 2*x
>
> y = f(3)
> print y, flag
> #------------------
> output:
> 6 0
>
<snip>
> (2) After being shocked by the above example, students start to put
> 'global' statements in every single function for every single
> variable. They don't understand what is going on, they just don't want
> to be bitten by the same bug, again.
So perhaps the students should be taught not to use the global statement at
all in situations like the one above:
def f(x):
return 2*x, 1
y, flag = f(3)
And if they need to store state, it may be time to introduce classes:
class F:
def foo(self, x):
self.flag = 1
return 2*x
f = F()
y = f.foo(3)
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list