Python Functions

A function is a block of statements that perform a specific task, which can be used multiple times within a program. In Python, as with a lot of languages, there are a number of functions built in, however, it is also possible to create user defined functions. The statements within a function are only executed once the function is called, so, if the function is never called then they won’t run. In Python, a function can be defined and called as follows.

# Function definition.
def function_name(arguments):
   # Statement(s) to execute.

# Function call.
function_name(arguments)

When a function is defined it always starts with the keyword ‘def’, followed by the function name and any arguments that need to be passed to it in parenthesis.  If there are no arguments to be passed to the function, then the parenthesis still need to be present, but with nothing enclosed. As with variables, function names can contain letters, numbers and underscores, but must start with either a letter or underscore. Indentation of code within a function is necessary, as with ‘if’ statements and loops, to prevent indentation errors.

Below is a simple example of a function definition and call, where no arguments are passed to the function, it just prints out the message, ‘Hello World!’, to the console.

def hello():
   print("Hello World!")

hello()

The ‘print’ statement is an example of one of Python’s built in functions, where ‘print’ is the name of the function and the string ‘Hello World!’ is an argument being passed to it.

The above example can be enhanced to include arguments, such as a person’s name. Here two arguments, first name and last name, are passed to the function, separated by a comma. The ‘+’ symbols are used to concatenate the various parts of the string together.

def hello(fname, sname):
   print("Hello " + fname + " " + sname)

hello("Fred", "Bloggs")

The resulting output from this is as follows.

Hello Fred Bloggs

The ‘print’ statement in the above example can be re-written to utilise the ‘format’ function. Here the arguments included in the string are replaced with ‘{}’ and then added using the ‘format’ function. The resulting output is still the same as above.

def hello(fname, sname):
   print("Hello {} {}".format(fname, sname))

hello("Fred", "Bloggs")

As well as being able to pass one or more arguments into a function, it is also possible for a value to be returned. The example below again takes two arguments, ‘fname’ and ‘sname’, and returns a message string incorporating the two arguments, which is output to the console. This again produces the same output as above.

def hello(fname, sname):
   return ("Hello {} {}".format(fname, sname))

print(hello("Fred", "Bloggs"))

If the message being returned from the function is required later on in the program, it could first be assigned to a variable.

def hello(fname, sname):
   return ("Hello {} {}".format(fname, sname))

hello_message = hello("Fred", "Bloggs")
print(hello_message)

Variable Scope

Variables in Python can be defined anywhere within a program. The scope of a variable refers to the area of a program that it can be used. Variable scope in Python can either be local or global.

Variables that have a global scope are defined outside of a function and are available to the whole program, whereas, variables with a local scope are defined within a function and are only accessible within the function it is defined. It is possible to have a global and local variable with the same name, both of which have their own value. This is demonstrated below.

fname = "Stuart"
def hello():
   fname = "Fred"
   return fname

print("Hello {}".format(hello()))
print("Hello {}".format(fname))

The results displayed in the console are as follows.

Hello Fred
Hello Stuart

The first ‘print’ statement above utilises the ‘hello’ function and displays the ‘fname’ variable that has local scope to the function, whilst the second statement displays the global version of the ‘fname’ variable as part of the message.

In order to use globally scoped variables inside a function, the ‘global’ keyword needs to be used.

fname = "Stuart"
def hello():
   global fname
   fname = "Fred"
   return fname

print("Hello {}".format(hello()))
print("Hello {}".format(fname))

Now that the ‘global’ keyword has been used the output has changed.

Hello Fred
Hello Fred

Both messages include the name ‘Fred’ because the ‘hello’ function is called in the first ‘print’ statement, which now changes the value of the global ‘fname’ variable. Note that, if the order of the above print statements was reversed, the first message output to the console would include the name ‘Stuart’ because the ‘hello’ function that changes the ‘fname’ variable wouldn’t get called until the second ‘print’ statement.