In this lesson we will look at Python 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)
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:
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.
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.
str
function, passing the argument 3.str
function calculates a return value, in this case the string '3'.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:
str
function, passing the argument 3.str
function calculates a return value, in this case the string '4'.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
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!
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.
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:
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
You can define your own functions in Python using def.
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()
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)
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)
If you found this article useful, you might be interested in the book Functional Programming in Python, or other books, by the same author.
<<PrevCopyright (c) Axlesoft Ltd 2020