Global & Parameter Passing - Python

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

Global Variables

One way to pass values into subroutines is by using global. Global variables are available throughout the program without the need to include them in the parameters. In the example below we have declared a variable and we have 2 subroutines which use this, one to just print and the other to change the value:

myGlobal = 5

def func1():
    myGlobal = 42

def func2():
    print myGlobal

func1()
func2()

This program will actually print '5' and not 42, because the change within func1() is not retained. However it will be if you add a global command:

myGlobal = 5

def func1():
    global myGlobal
    myGlobal = 42

def func2():
    print myGlobal

func1()
func2()

This code will print '42' because the variable will be changed in func1().

Parameters

In python a subroutine can have parameters which must be passed into the subroutine when it is called. Failure to do so will cause a syntax error. For example you could create a subroutine and pass it a value as a parameter, this is the subroutine:

def answer(person):
     if person=="Wayne":
          print("yes")
     else:
          print("no")

You would pass the value when you call the subroutine:

answer(name)

Or:

answer("Wayne")

Default Parameters

You can specify a default value for a parameter, this will be used if no parameter is passed. For example:

def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")