Game Development Reference
In-Depth Information
6 - Dragon Realm
print('Hello, ' + fizzy)
print('Say hello to Alice.')
fizzy = 'Alice'
sayHello()
print('Do not forget to say hello to Bob.')
sayHello()
When we run this code, it looks like this:
Say hello to Alice.
Hello, Alice
Do not forget to say hello to Bob.
Hello, Alice
This program's sayHello() function does not have a parameter, but uses the global
variable fizzy directly. Remember that you can read global variables inside of functions,
you just can't modify the value stored in the variable.
Without parameters, we have to remember to set the fizzy variable before calling
sayHello() . In this program, we forgot to do so, so the second time we called
sayHello() the value of fizzy was still 'Alice' . Using parameters makes function
calling simpler to do, especially when our programs are very big and have many functions.
Local Variables and Global Variables with the Same Name
Now look at the following program, which is a bit different. To make it clear to see, the
global variable has been bordered with a line, and the local variable has been bordered with
dots.
def spam(myName):
print('Hello, ' + myName)
myName = 'Waffles'
print('Your new name is ' + myName)
myName = 'Albert'
spam(myName)
print('Howdy, ' + myName)
If we run this program, it would look like this:
Hello, Albert
Your new name is Waffles
 
Search WWH ::




Custom Search