Global & Parameter Passing - Python

From TRCCompSci - AQA Computer Science
Revision as of 21:31, 25 June 2018 by Admin (talk | contribs) (Created page with "=Global Variables= One way to pass values into subroutines is by using global. In the example below we have declared a variable and we have 2 subroutines which use this, one t...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Global Variables

One way to pass values into subroutines is by using global. 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().