Last Updated:

Creating and working with functions in Python

A function is a piece of code in a program that can be used in some way anywhere in the program.

We can say that a function is a small subroutine.

In the function itself, you must write code that will be executed when the function is called.

In Python, all functions have parentheses, never forget about them!

It is profitable to write a function when it is necessary to perform some action several times. You can write code that performs this action several times, or you can write a function that will be called by name and this call will take only one line of code instead of all the lines that would have to be written to perform some operation.
This approach is called procedural programming. By writing a function and using it in the future when programming, we significantly reduce the number of lines of code.

In the function, you can prescribe any code that your soul desires, the main thing is to adhere to some rules.


Create your own function

The Python syntax for creating a function is as follows:

  1. We prescribe the service word def;
  2. Prescribe the name of your function. The name must be written in letters of the Latin alphabet and must not begin with a number or number;
  3. Put parentheses () after the function name. These parentheses indicate the parameters of the function (the arguments that the function takes);
  4. A colon is placed : ;
  5. Below is the entire code that you want to write in the form of a function;

As an example, let's create a function that displays the word 'Hello' on the screen


The feature is ready!

Now let's call her

A function can have parameters (take some arguments) or not have them (not accept arguments at all).

For example, we want to calculate the product of two numbers and display the result on the screen.

To do this, you will need to create a function with a name and specify in parentheses the corresponding parameters of this function.

The parameters are variables that will be used in the calculation in the function.


The feature is ready!

Let's call it for execution. To do this, you need to specify the name of the function and pass two numeric arguments.


Function Overload

A function overload is a deliberate extension of the functionality of a previously created function.

To overload a function, you need to create another function with exactly the same name, but specify different arguments (a different number).

Overload the calculation(a, b) function created earlier, let it multiply three numbers instead of two.


Overloaded function is ready!

Let's call a simple and overloaded function, and then enjoy the result...


In this simple way, we figured out "creating and working with functions in Python"!