Python informer

Improve your Python coding skills

Functions

Introduction

In this lesson we will look at Python functions:

  • Built in functions
  • Why use functions
  • How to call functions
  • Defining your own functions

Built in functions

We have already used several of Python’s built-in functions. These are functions that are always available for you to call whenever you need them.

Here are a few examples. str is a function that converts any value into a string, for example:

s = str(3)      # s now equals '3'

print is a function that displays a value in the console window. You will have use this already, many times:

print('Hello')

inputis slightly more involved. It displays a prompt to the user, in the console window. Then it waits for the user to type a response, and returns a string containing whatever the user typed in:

name = input('What is your name?')
print('Hello', name)

Why use functions

A function encapsulates some program logic - the code required to do some particular thing. It hides the code so that you can make use of the functionality without having to know or care what is happening inside the function. This allows the programmer to:

  • reuse code you have already written, rather than having to type it in every time.
  • simplify complex code by breaking it down into smaller parts.
  • share code with other people.
  • hide complicated code (like print()) so you can concentrate on what you are trying to do.
  • keep code secret, if you want to sell it to other people.

This applies to the Python built-in functions, and also to other functions that exist in optional Python libraries that you can install, and also to code that you might write yourself.

How to call functions

You already know how to call a function, we have done it quite a few times so far. But now we will look at it in a bit more detail.

s = str(3)

The str function takes one value (called a parameter or argument - the two terms are used interchangeably). In this case it is 3.

  1. To execute this line of code, Python first calls the str function, passing the argument 3.
  2. The str function calculates a return value, in this case the string ‘3’.
  3. Python assigns the return value to the variable s

Here is another case:

s = str(2 + 2)

In this case, there is an extra stage because the parameter passed in is the result of a calculation 2 + 2. This calculation is performed first, so:

  1. The parameter is evaluated, resulting in 4.
  2. Python calls the str function, passing the argument 3.
  3. The str function calculates a return value, in this case the string ‘4’.
  4. Python assigns the return value to the variable s

No we will look at a slightly different case, print. This function does something (displays something on the console) - we sometimes call this a side effect. But print doesn’t return anything, we only call it for its side effect:

print('Hello')

In fact, every Python function returns something. By default, if a function doesn’t have anything useful to return, it returns None (a Python value that represents nothing). When we call print we don’t assign the return value to a variable, so it just gets ignored.

Finally we have the input function. This function does something (gets input from the user) and returns something (whatever the user typed in). All functions usually either do something, or return something, or both, otherwise there isn’t much point calling it!

Optional parameters

input is usually called with one parameter. However, you can call it with no parameters. If you do that, it won’t display anything but it will still wait for the user to type something. We say that the parameter for input is optional (you can choose not to have it).

Compare this with str. That function must be called with one parameter, otherwise Python will throw an error.

Named optional parameters

print has some named optional parameters. One such parameter is end. The end parameter tells print what character it should place at the end of the print statement:

print(1)
print(2)
print(3)

By default print will use a newline after each call, so the code above will print:

1
2
3

If you wish you can tell print to use a different character, for example : instead of newline:

print(1, end=':')
print(2, end=':')
print(3, end=':')

This will print each value on the same line, with a : after each one.

1:2:3:

Variable number of arguments

print is quite unusual in that you can supply as many values as you like, and it will print them all, separated by spaces:

print(1, 2, 3, 4)
1 2 3 4

Defining your own functions

You can define your own functions in Python using def.

Printing @s

Here is a simple program to print 3 @ characters:

def print_3_ats():
    print('@' * 3)

The first line is the definition of the function. It starts with the keyword def followed by the name of the function with a pair of brackets. The colon character completes the definition (just like a loop or an if statement).

Under that is the body of the function, the part which actually prints the three “at”s. Remember that '@' * 3 is equivalent to '@@@'.

If you type this into the Python editor and run it, you will see that nothing actually happens. Your program just defines a function, it doesn’t actually execute the code. Python just remembers that when you call the function print_3_ats it should execute the print statement.

To define the function and run it, you need to do this:

def print_3_ats():
    print('@' * 3)
    
print_3_ats()

Printing more @s

Suppose, instead out printing 3 @s you wanted to print out a different number, in fact any number. You can rewrite the function like this (notice it has a different name):

def print_ats(n):
    print('@' * n)

We have given the function a parameter n to control how many characters get printed. Whatever value we pass in as n controls how many characters are printed:

print_ats(5)
print_ats(2)

Returning a value

Sometimes we use functions to calculate a value and return the result. Here is an example of a function which returns the square of x (that is, x times x):

def square(x):
    return x*x

You would call it like this:

answer = square(4)
print(answer)