Create your own game
eng   рус

Functions in Python

Previous tutorial: Collections in Python
Next tutorial: Classes in Python

Functions is one of the most important concepts in all programming languages. In this tutorial we'll examine functions in Python.

Function - is a block of code that can be executed many times from different parts of program. There are definition of a function and a call. In definition we put the code that will be executed during the call.

def - function definition in Python

Definition of a function consists of a header and a body. Header consists of keyword def, name of a function (can be any Python identifier), parameters of a function enclosed in brackets and a colon. In body we can put any code we want. Body of function must be indented. Let's see the example of a function that will just print string of text:

# function definition def print_hello (): print("Hello!!!"); # now we can make calls of function print_hello print_hello() print_hello() print_hello()

This code will output three lines "Hello!!!" text. Call of a function consists of function name and list of arguments enclosed in brackets. Here print_hello have zero arguments.

Such function will make the same job every time it's called. We can get different outcome by using parameters to get some data from outside of function.

Passing arguments to function

Let's change our function so it will print any arbitrary text of string. When user will call our function, it will print the text user have passed:

def print_text (text): print(text); print_text("Hello!!!") print_text("How are you?") # Output: Hello!!! How are you?

In the header of the function we added one parameter text. Inside function it will behave like common variable. So, in this example we just print it. The question is: how text gets it's value? When we make a call of a function, user passes argument and inside function this argument is assigned to parameter text. Here, in first call text is equal to "Hello!!!" and in the second call - "How are you?".

Functions can have many parameters/arguments:

def add (a,b): sum = a + b print(sum) add(1, 2) add(8428, 378287)

Function add sums two passed arguments and prints result. The order of arguments is matter. First argument is assigned to first parameter a and so on.

Returning value of a function - return statement

Function add prints the result of addition. Though, the name of a function supposes just addition. Let's rewrite it so it will return result and then there is user's responsibility:

def add (a,b): sum = a + b return sum add(1, 2) # nothing will happen a = add(8428, 378287) print(a) print(add(5,5))

return statement will pass back any data we want to the caller. We can say that function is evaluated to some value (the one that is returned).


In this tutorial we've learned basic capabilities of functions in Python programming language. There are more, but we'll learn them a bit later.


No comments yet