Python Basics 102: Introduction to Python Functions.
Tags: python, beginners, codenewbie, datascience
Published: 2021-07-31 17:27:33

**Hello world**, In the previous [post](https://dev.to/billyndirangu/python-basics-101-23nk) i introduced you to Python programming language, a high level language.
In this second post I am going to be taking you through **python Functions.**  

## Python Functions
~~_everything we do comprises of a function somewhere._~~
So, what are functions in python! 
* A **function** is a block of code that has statements that perform a specified task.
* They help in breaking down a program when it grows big.
* Functions minimize the *repetition* of code, hence they're **reusable.**

<!-- ### Content
- Defining Functions
- Uses of functions 
- lambda / Anonymous functions
- methods 
- Applications of functions 
-->
Let us define a function:
We use the **def** keyword to define a function:
```python
# define a function that says Hi.
def greet():
    print("Hello")

#calling the function
greet()
#prints> Hello
```
🤯 Awesome!
```python
# structure of a function
def function_name(paramters):
    """docstring"""
    statement(s)
```
 
A python function consists of the following:
- the `def` keyword, marks the beginning of a function 
- A function name to identify the purpose of  the function, Function names follow the same guide rules of **[pep8 naming conventions](https://www.python.org/dev/peps/pep-0008/#naming-conventions)**.
- parameters to which values to our functions.
- A colon **(:)** to mark the end of a function definition.
- In the body start with a `"""docstring"""`, to explain what the function does.
- One or more valid python **statements** that make up the function body.
- The `return`(optional) statement that returns a value to the function.

##Python Function Arguments
Functions takes variables as arguments.
Ways of defining arguments; using **default**, **keyword** and  **arbitrary arguments**. 
Defining functions with parameters. Parameters are identifiers in the function definition parentheses
```python
#function parameters
def greet(name, msg):
  print(f"Hello {name}, {msg}")

#call the function with the arguments
greet('Mark', 'Good Evening')
#prints> Hello Mark Good Evening
```
Here, the function `greet()` has two parameters `name, msg`
When the function is called, the two `parameters` are passed as `arguments`.

##Variable Function Arguments
A function can take a variable number of arguments.
- **Function Default Arguments**
```python
def greetings(name, msg="How are you?"):
    print(f"Hello, {name} {msg}")

#positional arguments.
greetings('Asha')
#> Hello, Asha How are you?
```
Even if we call the function with just one argument, it will complete smoothly without an error unlike in the previous function.
When an argument for `msg` is provided in function call, it will overwrite the **default argument**.

##Python Keyword Arguments
When a function is called with values, they get assigned to their specific positions.
But this can be changed when calling a function, the order can be altered with keywords, like in the above function we could call it like this:
```python
#keyword arguments in order
greetings(name="fast furious", msg="is out!")

#keyword arguments out of order
greetings(msg="is out!", name="Vin")
```
Well give it a try, everythings works just fine.

##Python Arbitrary Arguments
At times you might not know the number of arguments to be passed in a function.
In situations like this, python allows the use of an _asterisk (*)_ to denote arguments. example:
```python
def greet(*names):

   for name in names:
       print(f"Hello {name}.")

greet('juma', 'larry', 'lilian')
#> Hello juma.
#> Hello larry.
#> Hello lilian.
```
##Python Recursion
Recusion with python functions.
A repeated procedure can be reffered to as a **Recursion**. 
A recursive function, is a function that calls itself.
```python
def recurse():
    #statements
    recurse() #recursive call

recurse()
```

An example:
```python
#finding the factorial of a number
def factor(x):
  """
  this function finds the factorial of a given number
  factorial number is the product of a 
  number starting from 1 to that number itself
  """
  if x == 1:
    return 1
  else:
    return (x * factor(x-1))


num = 3
print(f"factorial is:  {factor(num)}")
```
####Pros of Recursion Functions
- Makes code look clean and elegant.
- Breakdown of complex tasks into smaller sub-tasks.
- Sequencing is easier compared to nested iteration.

###Cons 
- They are difficult to debug.
- Recursive calls take alot of memory and time.
- Hard to read or follow.

##Anonymous Functions
An anonymous function is a function that has no name.
They are also called **lambda** functions.
Defining a lambda function:
```python
#syntax:
lambda arguments: expression
```
They can have multiple arguments but only **one expression**.
working example:
```python
#sum of numbers
sum = lambda x: x+2
print(sum(2))
#> 2+2= 4

#multiple args
product = lambda x, y: x*y
print(product(2, 6))
#> 2*6 = 12
```
Lambda functions are used when a nameless function is required for a short period of time.
They are best used with in-built functions, **filter()** & **map()**.[Read more](https://www.programiz.com/python-programming/anonymous-function)


That's it for now, Hope you enjoyed reading this article.
let us learn python!!
Be cool, Keep coding.