Game Development Reference
In-Depth Information
6 - Dragon Realm
# The global variable was not changed in funky():
print(spam) # 42
It is important to know when a variable is defined because that is how we know the
variable's scope. A variable is defined the first time we use it in an assignment statement.
When the program first executes the line:
12. cave = ''
...the variable cave is defined.
If we call the chooseCave() function twice, the value stored in the variable the first
time won't be remember the second time around. This is because when the execution left
the chooseCave() function (that is, left chooseCave() 's local scope), the cave
variable was forgotten and destroyed. But it will be defined again when we call the function
a second time because line 12 will be executed again.
The important thing to remember is that the value of a variable in the local scope is not
remembered in between function calls.
Defining the checkCave() Function
19. def checkCave(chosenCave):
Now we are defining yet another function named checkCave() . Notice that we put the
text chosenCave in between the parentheses. The variable names in between the
parentheses are called parameters .
Remember, for some functions like for the str() or randint() , we would pass an
argument in between the parentheses:
>>> str(5)
'5'
>>> random.randint(1, 20)
14
When we call checkCave() , we will also pass one value to it as an argument. When
execution moves inside the checkCave() function, a new variable named chosenCave
will be assigned this value. This is how we pass variable values to functions since functions
cannot read variables outside of the function (that is, outside of the function's local scope).
Search WWH ::




Custom Search