Difference between revisions of "Global & Parameter Passing - Python"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(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...")
 
(Global Variables)
Line 32: Line 32:
  
 
This code will print '42' because the variable will be changed in func1().
 
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.
 +
 +
=Default Parameters=
 +
You can specify a default value for a parameter, this will be used if no parameter is passed. For example:
 +
 +
<syntaxhighlight lang=python>
 +
def my_function(country = "Norway"):
 +
  print("I am from " + country)
 +
 +
my_function("Sweden")
 +
my_function("India")
 +
my_function()
 +
my_function("Brazil")
 +
</syntaxhighlight>

Revision as of 22:49, 25 June 2018

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().

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.

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")