[Tutor] An unknown error in my program

Joel Goldstick joel.goldstick at gmail.com
Sun Dec 25 12:26:15 CET 2011


On Sun, Dec 25, 2011 at 6:00 AM, Lie Ryan <lie.1296 at gmail.com> wrote:
> On 12/25/2011 09:46 PM, Joel Goldstick wrote:
>>
>>
>> You can either move the stuff at the top of your program into main, or
>> you could pass the outer new
>> into main as a parameter:    main(new):
>
>
> the third alternative is to use the global keyword, e.g.
>
> # declare a global named 'new'
> new = 0
>
> def increment_new():
>    # tell python to use the global 'new' instead of
>    # creating a local 'new'
>    global new
>
>    new += 1
>
> print new
> increment_new()
> print new
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Since this is a tutor mailing list, many questions come from people
learning not only python, but programming in general.  Lie is right in
showing that you can let your function know that you want it to know
about the global called new.  But I think this is generally not a good
approach.

To get good at python you need to understand scope and namespaces.
The value of using functions is that they let you write small self
contained code that accomplishes some purpose.  The purpose should be
clear from the name of the function.  Once your function works as you
like it, you don't need to worry about how it works.  You can just
call it from somewhere else in your program, knowing that it will do
what it does.  Using a global messes this up.  Now, when  you call
your function it will fail unless there is some variable named 'new'
in some outer namespace.  Your function is no longer self contained.

Since the OPs code is so small, there may not be a need to use a
function at all, but since he chose to go that route, the data that
the function needs should be declared within the function.  If that
data is created elsewhere it should be passed to the function via
parameters.  If the function creates a result that will be needed
later, it should be returned by the function.

So, my point is that learning about the value of and aspects of
writing good functions is more instructive than going with the global
declaration.

-- 
Joel Goldstick


More information about the Tutor mailing list