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


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:


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:


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:


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


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.


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)


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:


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)

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


Tag cloud

2d arrays abstract data type alignment and array arrays bezier curve built-in function close closure colour comparison operator comprehension context conversion data types design pattern device space dictionary duck typing efficiency encryption enumerate filter font font style for loop function function composition function plot functools generator gif gradient greyscale higher order function html image processing imagesurface immutable object index inner function input installing iter iterator itertools lambda function len linspace list list comprehension logical operator lru_cache mandelbrot map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path positional parameter print pure function radial gradient range recipes recursion reduce rgb rotation scaling sequence slice slicing sound spirograph str stream string subpath symmetric encryption template text text metrics transform translation transparency tuple unpacking user space vectorisation webserver website while loop zip

Copyright (c) Axlesoft Ltd 2020