In the previous post I introduced you to Python programming language, python installation and python fundamentals.
In this post we will go through Python functions
FUNCTIONS IN PYTHON
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions minimize the repetition of code, hence they are reusable.
Below are the rules to define a function in Python.
- Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
- Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
- In the body start with a """docstring""", to explain what the function does.
- The code block within every function starts with a colon (:) and is indented. Check Pep 8
- The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Function syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Function Example
# define a function that says Hello World.
def greet():
print("Hello World")
#calling the function
greet()
#prints> Hello World
Calling a Function
When you want to use a function, you just need to call it. A function call instructs Python to execute the code inside the function.
Returning a value
A function can perform a task like the greet() function. Or it can return a value. The value that a function returns is called a return value.
To return a value from a function, you use the return statement inside the function body.
Python Parameters and Arguments
It’s important to distinguish between the parameters and arguments of a function.
- A parameter is a piece of information that a function needs. And you specify the parameter in the function definition.
- An argument is a piece of data that you pass into the function.
Here is an Example to help us differentiate a parameter and an argument.
def sum(a, b):
return a + b
total = sum(10,20)
print(total)
In this example, the sum() function has two parameters a and b, and returns the sum of them.
In the following function call, a will be 10 and b will be 20 inside the function body. These values 10 and 20 are called arguments.
Python Decorator.
A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
Syntax for a python decorator
from fastapi import FastAPI
app = FastAPI()
#Here is the decorator
@app.get("/")
async def root():
return {"message": "Hello World"}
Python Recursive Functions
A recursive function is a function that calls itself and always has condition that stops calling itself.
Python recursive function examples
1.Count Down to Zero
Suppose you need to develop a countdown function that counts down from a specified number to zero.
The following defines the count_down() function:
def count_down(start):
""" Count down from a number """
print(start)
Example
def count_down(start):
""" Count down from a number """
print(start)
# call the count_down if the next
# number is greater than 0
next = start - 1
if next > 0:
count_down(next)
count_down(3)
Output:
3
2
1
- Using a recursive function to calculate the sum of a sequence
Suppose that you need to calculate a sum of a sequence e.g., from 1 to 100. A simple way to do this is to use a for loop with the range() function:
def sum(n):
total = 0
for index in range(n+1):
total += index
return total
result = sum(100)
print(result)
Output:
5050
Python Lambda Expressions
Lambda Function, also referred to as 'Anonymous function' is same as a regular python function but can be defined without a name. While normal functions are defined using the def keyword, anonymous functions are defined using the lambda keyword.
lambda expression syntax:
lambda arguments: expression
Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.
Example:
double = lambda x: x * 2
print(double(5))
#sum of numbers
sum = lambda x: x+5
print(sum(5))
#> 5+5= 10
#multiple args
product = lambda x, y: x*y
print(product(5, 10))
#> 5*10 = 50
I hope this was helpful. Let's engage in a discussion on anything that I should add to make this article better.
Stay safe
Mask up
Coders gonna code!
Top comments (0)