Game Development Reference
In-Depth Information
Howdy, Albert
This program defines a new variable called
myName
and stores the string
'Albert'
in
it. Then the program calls the
spam()
function, passing the value in
myName
as an
argument. The execution moves to the
spam()
function. The parameter in
spam()
is also
named
myName
, and has the argument value assigned to it. Remember, the
myName
inside
the
spam()
function (the local scope) is considered a different variable than the
myName
variable outside the function (the global scope).
The function then prints
'Hello, Albert'
, and then on the next line changes the
value in
myName
to
'Waffles'
. Remember, this only changes the local
myName
variable that is inside the function. The global
myName
variable that is outside the function
still has the value
'Albert'
stored in it.
The function now prints out
'Your new name is Waffles'
, because the
myName
variable in the local scope has changed to
'Waffles'
. The execution has
reached the end of the function, so it jumps back down to where the function call was. The
local
myName
is destroyed and forgotten. The next line after that is
print('Howdy, '
+ myName)
, which will display
Howdy, Albert
.
Remember, the
myName
outside of functions (that is, in the global scope) still has the
value
'Albert'
, not
'Waffles'
. This is because the
myName
in the global scope and
the
myName
in
spam()
's local scope are different variables, even though they have the
same name.
Where to Put Function Definitions
A function's definition (where we put the
def
statement and the def-block) has to come
before you call the function. This is like how you must assign a value to a variable before
you can use the variable. If you put the function call before the function definition, you will
get an error. Look at this code:
sayGoodBye()
def sayGoodBye():
print('Good bye!')
If you try to run it, Python will give you an error message that looks like this:
Traceback (most recent call last):
File "C:\Python31\foo.py", line 1, in <module>
sayGoodBye()