Functions

By Martin McBride, 2018-08-05
Tags: built-in function str input print def optional parameter named parameter
Categories: python language beginning python


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

input is 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 other functions that exist in optional Python libraries that you can install. It also applies 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

Now 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). Most functions either do something, or return something, or both (otherwise there wouldn't much point calling the function at all).

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. Python will throw an error if you pass the wrong number of parameters.

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 that 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 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 of printing 3 @s you wanted to choose the number of @s when you call the function. 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)

See also

If you found this article useful, you might be interested in the book NumPy Recipes or other books by the same author.

Join the PythonInformer Newsletter

Sign up using this form to receive an email when new content is added:

Popular tags

2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest