Python Functions
On this page
Python functions
Python functions is a block of statements that return the specific task.
Some benefits of using functions are:
- increase code readability
- increase code reusability
Simple function
To build a function, use def
keyword and name of function, with parenthesis:
# A simple Python functiondef fun():"""This is doc; fun means function but also funny!"""print("Welcome to the jungle!")
After you declare a function, you can use it:
# Driver code to call a functionfun()
Return statement
With return
keyword in a body of Python function, you specify a return point and object.
To default every Python function return None
if return statement is not specified.
Function with arguments
Python function accepts some parameters, declared into parenthesis:
def add_something(one, two):"""Add some stuff"""result = one + tworeturn result
And call it:
# Call with strings...print(add_something("a", "b")) # ab# ...and with integerprint(add_something(1, 2)) # 3
Default arguments
Python function parameters accept also default arguments:
def print_point(x=0, y=0):"""Print point position"""print("x: ", x)print("y: ", y)
And call it:
# No specify argumentsprint_point() # x: 0 and y: 0# Specify one argumentprint_point(10) # x: 10 and y: 0# Specify two argumentsprint_point(10, 20) # x: 10 and y: 20# Specify two arguments with nameprint_point(y=10, x=20) # x: 20 and y: 10
Typed function
Python function accepts type information of parameters and return statement (-> str
):
def person(name: str, age: int) -> str:"""Return person informations"""return f"{name} is {age} year old"
And call it:
print(person("Matteo", 38)) # Matteo is 38 year oldprint(person("Marco", 32)) # Marco is 32 year oldprint(person("Arthur", 42)) # Arthur is 42 year old
Arbitrary arguments
Python function accepts also an undefined numbers of arguments of two types:
- positional arguments; stored in a tuple
- keyword arguments; stored in a dictionary
Positional arbitrary arguments
def concatenate(*strings):return " ".join(strings)
And call it:
print(concatenate("Metal", "is", "forever")) # Metal is forever
Keyword arbitrary arguments
def book(author, title, **infos):b = {"author": author,"title": title}b.update(infos)return b
And call it:
lord_of_the_rings = book("J. R. R. Tolkien", "Lord of The Rings", year=1954, publication=2)print(lord_of_the_rings) # {'author': 'J. R. R. Tolkien', 'title': 'Lord of The Rings', 'year': 1954, 'publication': 2}silmarillion = book("J. R. R. Tolkien", "Silmarillion", pages=688, language="english")print(silmarillion) # {'author': 'J. R. R. Tolkien', 'title': 'Silmarillion', 'pages': 688, 'language': 'english'}
Anonymous functions
In Python, an anonymous function means that a function is without a name. As we already know the def
keyword is used to define the normal functions and the lambda
keyword is used to create anonymous functions, and after that, the arguments is specify.
cube = lambda number: number * number * numberprint(cube(7)) # 343
Function decorator
A function that is defined inside another function is known as the inner function or nested function. Nested functions can access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. This type of functions is called decorators.
def add_to_number(x):def inner(y):return x + yreturn inner
And call it:
add_five = add_to_number(5)result = add_five(6)print(result) # 11
Pass function as argument
We can pass a function as an argument to another function in Python.
def add(x, y):return x + ydef calculate(func, x, y):return func(x, y)
And call it:
result = calculate(add, 4, 6)print(result) # 10
Decorate other function
Instead of assigning the function call to a variable, Python provides a much more elegant way to achieve this functionality using the @
symbol.
def make_pretty(func):def inner():print("%" * 13)func()print("%" * 13)return inner@make_prettydef ordinary():print("I am ordinary")
And call it:
ordinary()# %%%%%%%%%%%%%# I am ordinary# %%%%%%%%%%%%%
Decorate with arguments
Is possible to pass arguments to function decorator
def make_pretty(symbol):def inner(func):print(symbol * 13)func()print(symbol * 13)return inner@make_pretty("+")def ordinary():print("I am ordinary")
And call it:
ordinary()# +++++++++++++# I am ordinary# +++++++++++++
Function generators
Function generators is a function that returns an iterator using the yield
keyword.
def fib(limit):a, b = 0, 1while b < limit:yield ba, b = b, a + b
And call it:
# Create a generator objectx = fib(200)# Iterate over the generator object and print each valuefor i in x:print(i)# 1# 1# 2# 3# 5# 8# 13# 21# 34# 55# 89# 144