#16 Functions in Python / Python Lessons for Beginners

by Alex
#16 Functions in Python / Python Lessons for Beginners

Previous lesson: Cycle for A function is a block of code that only runs when it is called. You can pass data known as parameters to a function. As a result, the function has the ability to return data.

Creating a Function

A function in Python is defined with the keyword def:

def my_function():
print("Hello from function")

Function Call

To call a function, use the function name followed by parentheses.

def my_function():
print("Hi from function")
my_function()

Conclusion:

Hello from the function

Parameters

Information can be passed to a function as a parameter. Parameters are listed after the function name, inside the brackets. You can add as many parameters as you want by separating them with a comma. The following example is a function with one parameter(fname). When the function is called, we pass the name, which is used inside the function to print the full name:

def my_function(fname):
print(fname + "Popov")
my_function("Andrei")
my_function("Vlad")
my_function("Nikita")

Output:

Andrey Popov
Vlad Popov
Nikita Popov

The default value of the parameter

In the following example you can see how to use the default parameter value. If we call a function without a parameter, it uses the default value:

def my_function(country="England"):
print("I'm from " + country)
my_function("Poland")
my_function("China")
my_function()
my_function("USA")

Output:

I am from Poland
I am from China
I am from England
I am from USA

Return value

To return a function value, use the operator return:

def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))

Output:

15
25
45

Related Posts

LEAVE A COMMENT