A function is like a mathematician–it turns coffee into theorems. Or more simply, it is a bunch of statements that accepts inputs, perform some computation based on defined rules, and returns a result as output. The subject is broader from a mathematical perspective, but here we focus on the essentials required to do Python well enough.
How to calculate the length of a string in Python?
The goal is to is “automate” repeated computations so that we do not have to write the same codes again when we want to perform that operation on an input. Just call the function that does it. For example, consider the squaring function:
def squareNumber(x): return x*x
We created a function! But that is a user-defined function; we will talk about this function again later. There are also inbuilt functions in Python that you simply have to call. An example is the print function. An example is:
print('Welcome to myhowtoonline.com - the universal repository of programming guides!')
Welcome to myhowtoonline.com - the universal repository of programming guides!
Syntax of User-defined Python Function
def function_name(parameters): '''docstring''' statements(s) return
Now let us break the above function syntax piece by piece.
- There is the keyword def that initiates every function block.
- A unique identifier or name (There are rules when choosing a name. But a simple name would do pending when you look up the rules).
- Arguments passed to the function.
- The function header is ended with a colon (:).
- Commenting makes code easier to read. So the documentation string (docstring) can be a valuable piece of a function.
- The main statements of the function; the computation the function does. This should be indented.
- A return statement; this is optional. It returns output from the function.
def greet(name): '''This function greets you, our reader, whose name has been passed in as string argument''' print('Hello, ' + name + '. Good day and welcome to myhowtoonline.com!')
Observe how the function was defined with every rule in the general syntax met, except the return keyword. Yes, it is optional.
We have learned how to define a function in Python. Next thing is to use them. What is the essence after all of defining functions we would not use? So remember that squaring function we defined earlier? Its time to make it work!
To call a function, we invoke the function name and pass arguments. Like this:
n = squareNumber(4)
I trust you understand what happened behind the scenes. Functions are not unique. For example, the square function can also be written as:
def squareNumber(x): return x**2
There you have it! You can now make your Python codes more organized and neat–by enveloping redundant codes into a function. If you are ready for the next step you can try our tutorial on how to make a simple python game or read more about basic math functions.