Python Beginners Guide - Functions
Tags: python, beginners, programming, challenge
Published: 2022-02-02 06:26:46

Moving forward from where we left of, In this article I am going to share about functions in python and how they are used.

Just like any other programming language, functions are used to enhance code usability, what exactly is a function?

## What is a Function?
A function can be defined as a block of code that will execute when it is called. They also help break large block of code into smaller parts.

Syntax
A general way to define a function in python is as below:
```python
def function_name(parameters):
    # Comment of what the function does
    [body]
    return result 
```
__*Breakdown of the Syntax*__
* def - it is a keyword needed before the function name followed by a pair of parentheses and a colon at the end.
* parameters - where you pass arguments of your function if any.
* Comment - elaborate in a few words what the function does, helps in readability of code.
* body - where you write the code block that describes what the function does.
* return - returns the result of the executed code.

## Types of Functions in Python
* Built-In functions - functions that come pre-installed after installing python.
* User-defined functions - functions created by the user to help them out
* lambda functions - also known as Anonymous functions. This are functions which are not declared with the `def` keyword.

### Built-In functions
Some of the most common built-in functions in python include:
* __`print()`__ - used when one needs an output printed.
* __`input()`__ - used to prompt the user to enter some input, the input is stored as a string.
```python
name = input("What's your name? ")
print("Nice to meet you " + name + "!")
```
when this program is run, the expected output will be:
```cmd
What's your name? "lary"
Nice to meet you lary!
```
* __len()__ - it helps when you need to find the length of a string, list, tuple or any other data type.
```python
str1 = "Hope you find this article useful"
print("The length of the string is :", len(str1))
```
Output
```cmd
The length of the string is : 33
```
Read more on in-built python functions [HERE](https://docs.python.org/3/library/functions.html)

### User-defined Functions
Apart from using the inbuilt functions, python allows users to define their own functions. In order for you define your own functions here is a quick walk through on how to do it.

## How to Define a Function
1. Use the `def()` keyword followed by the function name. The parenthesis should either contain parameters your function will take or stay empty.
```python
def learn():
```
2. Next, you will need to add code block of what your functions is meant to do.
```python
def learn():
    print("I am learning about Functions in Python")
```
3. Now you can call your function for it to execute.
```python
def learn():
    print("I am learning about Functions in Python")

learn()
```
If you run run this sample code, it is going to print the text enclosed in the parentheses

Let's take a look at an example with arguments being passed.
```python
def add_num(x,y,z):
    a = x+y
    b = x+z
    c = y+z
    print(a,b,c)
add_num(5,4,8)
```
## Docstrings
> Code tells you how; Comments tell you why.
— Jeff Atwood

Docstrings are what describe what your function does. They also serve as a mini documentation that helps out anyone trying to read your code to easily understand the function does.

They are placed immediately in the next line after declaring the function and are placed between triple quotation marks `'''`
```python
def hello():
    '''Prints Hello World.'''
    print("Hello World")
hello()
```

### Anonymous Functions
*Syntax*
```python
lambda arguments: expression
```
lambda functions can have any number of arguments but are limited to one expression.
An example:
```python
double = lambda x: x * 2

print(double(5))
```
This function doubles the x value, in our case 5 will be doubled hence giving the output 10.

Due to the depth coverage of python function, below I have shared resources to help you get extra knowledge on specific topics:

Other helpful resources to learn about Python Functions:
* [Functions in Python – Explained with Code Examples](https://www.freecodecamp.org/news/functions-in-python-a-beginners-guide/)
* [Python Anonymous/Lambda Function](https://bit.ly/3IUh4RV)

See you in the next one!

<a href="https://www.buymeacoffee.com/lary" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>

Connect With me at [Twitter](https://twitter.com/larymak1) | [GitHub](https://github.com/larymak) | [YouTube](https://www.youtube.com/channel/UCrT1ARRZfLOuf6nc_97eXEg) | [LinkedIn](https://www.linkedin.com/in/hillary-nyakundi)  |