Python Basics 102- Python Functions.
Tags: python, programming, datascience
Published: 2021-08-02 09:23:54

In the previous [post](https://dev.to/prestontoo/python-101-introduction-to-python-cm2) I introduced you to Python programming language, python installation and python fundamentals.
In this post we will go through **Python functions**

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f7aanb3w9m5n66dpa7gl.png)
 

###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](https://www.python.org/dev/peps/pep-0008/#naming-conventions)
* 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
```python
def functionname( parameters ):
   "function_docstring"
   function_suite
   return [expression]
```
####Function Example
```python
# 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.
```python
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
```python
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:
```python
def count_down(start):
    """ Count down from a number  """
    print(start)
```
####Example
```python
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:
```python
3
2
1
```
2. *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:
```python
def sum(n):
    total = 0
    for index in range(n+1):
        total += index

    return total


result = sum(100)
print(result)
```
Output:
```python
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:
```python
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:
```python
double = lambda x: x * 2

print(double(5))
```
```python
#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!**