Python functions can be very useful. Python functions store logical steps that can be reused.
The advantage with a function is it can be invoked, rather than having to always retype the lines of code that consist of the function.
The Python reserved word to store a Python function is ‘def’. If you start a line of code with ‘def’, it tells Python to store the function, but to only run it if it is called on later.
Python Functions Examples
The first two lines in this example are the Python function. The last line below it invokes the function. The Python function will not execute until it is invoked.
Invoking a Built-In Python Function
A Python function could be built-in, so all you have to do is invoke it.
>>> print big
In the above example, ‘max’ is the built-in Python function. The string inside the parenthesis is called the argument. The argument passes through the function. The ‘max’ function then returns the highest character of a string.
Other common built-in functions are ‘float’, and ‘int’. There are many built-in Python functions. However, A Python function you write yourself is called a user defined function.
A Python Function with Arguments
Look at the following Python function:
sum = x + y
Now you can invoke the function with two function arguments, as follows:
Invoking this function should cause ‘8’ to be printed.
Now look at a slightly modified version of the addition function:
sum = x + y
Notice the word ‘return’ was used. This gives you a return value, and it terminates the function. However, it does not print the value. You control where it prints, such as:
The number ‘3’ would be printed because that would be the return value.
You will not always need to write a Python function in your program, but if you catch yourself reusing code, it might be best to put that code in a Python function that can simply be invoked when you want to execute it.