/
๐Ÿ

Python Functions

https://docs.python.org/3.13/reference/compound_stmts.html#function-definitions
python
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:

python
# A simple Python function
def fun():
"""This is doc; fun means function but also funny!"""
print("Welcome to the jungle!")

After you declare a function, you can use it:

python
# Driver code to call a function
fun()

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:

python
def add_something(one, two):
"""Add some stuff"""
result = one + two
return result

And call it:

python
# Call with strings...
print(add_something("a", "b")) # ab
# ...and with integer
print(add_something(1, 2)) # 3

Default arguments

Python function parameters accept also default arguments:

python
def print_point(x=0, y=0):
"""Print point position"""
print("x: ", x)
print("y: ", y)

And call it:

python
# No specify arguments
print_point() # x: 0 and y: 0
# Specify one argument
print_point(10) # x: 10 and y: 0
# Specify two arguments
print_point(10, 20) # x: 10 and y: 20
# Specify two arguments with name
print_point(y=10, x=20) # x: 20 and y: 10

Typed function

Python function accepts type information of parameters and return statement (-> str):

python
def person(name: str, age: int) -> str:
"""Return person informations"""
return f"{name} is {age} year old"

And call it:

python
print(person("Matteo", 38)) # Matteo is 38 year old
print(person("Marco", 32)) # Marco is 32 year old
print(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

python
def concatenate(*strings):
return " ".join(strings)

And call it:

python
print(concatenate("Metal", "is", "forever")) # Metal is forever

Keyword arbitrary arguments

python
def book(author, title, **infos):
b = {
"author": author,
"title": title
}
b.update(infos)
return b

And call it:

python
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.

python
cube = lambda number: number * number * number
print(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.

python
def add_to_number(x):
def inner(y):
return x + y
return inner

And call it:

python
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.

python
def add(x, y):
return x + y
def calculate(func, x, y):
return func(x, y)

And call it:

python
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.

python
def make_pretty(func):
def inner():
print("%" * 13)
func()
print("%" * 13)
return inner
@make_pretty
def ordinary():
print("I am ordinary")

And call it:

python
ordinary()
# %%%%%%%%%%%%%
# I am ordinary
# %%%%%%%%%%%%%

Decorate with arguments

Is possible to pass arguments to function decorator

python
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:

python
ordinary()
# +++++++++++++
# I am ordinary
# +++++++++++++

Function generators

Function generators is a function that returns an iterator using the yield keyword.

python
def fib(limit):
a, b = 0, 1
while b < limit:
yield b
a, b = b, a + b

And call it:

python
# Create a generator object
x = fib(200)
# Iterate over the generator object and print each value
for i in x:
print(i)
# 1
# 1
# 2
# 3
# 5
# 8
# 13
# 21
# 34
# 55
# 89
# 144
Want to make your own site like this?
Try gatsby-theme-code-notes by Zander Martineau.
Life of Code