minor nit - example shows two functions that share a global variable

8 views
Skip to first unread message

Robert L

unread,
May 30, 2011, 4:22:57 PM5/30/11
to Building Skills Books
url: http://homepage.mac.com/s_lott/books/python/html/p01/p01c10_adv_func.html#the-global-statement

The following example shows two functions that share a global
variable.

ratePerHour= 45.50
def cost( hours ):
global ratePerHour
return hours * ratePerHour
def laborMaterials( hours, materials ):
return cost(hours) + materials

The above doesn't really emphasize the point of the global statement
because ratePerHour would have been properly resolved even if the
global statement was removed.

Recommend something like the example in "Global variables in Python"

url: http://stackoverflow.com/questions/423379/global-variables-in-python

globvar = 0

def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1

def print_globvar():
print globvar # No need for global declaration to read value
of globvar

set_globvar_to_one()
print_globvar() # Prints 1

The global declaration is in set_globvar_to_one because that is where
you interact with globvar -- but if, like print_globvar, a function is
only reading the value of globvar, not writing it, then you don't need
a special global declaration to access the global variable's value.
Reply all
Reply to author
Forward
0 new messages