⊗pyPmUFInr 198 of 208 menu

Basics of Working with User-Defined Functions in Python

In Python, in addition to using standard functions and methods, you can create and use your own functions.

Let's look at the syntax for creating your own function. To declare it, you need to write the keyword def, then its name and parentheses in which you can specify parameters. Next, put a colon, after which the desired code is written in the lower block (function body). The function body should be indented, like in any other block of code.

For example, let's create a function func:

def func(): ''' the body of the function, in which the code for execution is written '''

Let's make the function func output an exclamation mark:

def func(): print('!')

Let's now call our function. To do this, you need to write its name and parentheses:

def func(): print('!') # We call our function: func() # '!'

We can call our function several times - in this case, each call to the function will produce a new output to the screen:

def func(): print('!') func() # '!' func() # '!' func() # '!'

In Python, a function must be called below its declaration:

func() # will print an error def func(): print('!')

Make a function that will output your first and last name.

Make a function that will print the sum of 3 and 6.

byenru