6 C
Jaipur
Tuesday, January 26, 2021

# 7 Python Function Examples with Parameters, Return and Data Types

### Twitter launches new website to fight ‘fake news’

Functions are code snippets in a block that is assigned a name. It takes input, performs computation or an action and returns the output.

Functions enhances the reusability of the code.

In this tutorial, we’ll discuss the following examples:

1. Basic Python Function Example
2. Python Built-In Functions
3. Python User-Defined Functions
4. Python Function Parameters
5. Python Function Unknown Number of Parameters
6. Python Function Return Value
7. Datatype for Parameter s and Return Value

### 1. Basic Python Function Example

The following is an example python function that takes two parameters and calculates the sum and return the calculated value.

```# function definition and declaration
def calculate_sum(a,b):
sum = a+b
return sum

# The below statement is called function call
print(calculate_sum(2,3)) # 5
```

There are two broad categories of functions in Python: in-built functions and user-defined functions.

### 2. Python Built-In Functions

There are many functions that come along with Python, when it is installed. The user need not worry about the functions’ definitions. print() is one of the most commonly used in-built functions in Python.

```print("Hello world")
print(len("My name is Aanisha Mishra"))
```

Some more examples of such functions are : len(), str(), int(), abs(), sum(), etc.

All built-in functions supported by Python3 is here.

### 3. Python User-Defined Functions

User-defined functions are declared using the def keyword. The keyword should be followed by the function name.

```def calculate_si_amount(principal, rate, time):
interest =  (principal*rate*time)/100
return principal+interest
```

In this function, the final amount is calculated by applying simple interest to principal. calculate_si_amount is the function name. principal, rate and time are the parameters and the function is returning the calculated data.

It is not necessary for a function to accept parameters and return values. It can either do both, or one of them, or none. Below is an example of a function which does not take any parameter but returns data.

```from random import seed, random
from random import random

def generate_random_number():
seed(10)
return random()
```

### 4. Python Function Parameters

A function can have default parameters.

```def multiply(a, b=10):
return a*b

multiply(12) # 120
multiply(2, 3) # 6
multiply(b=9) # error: None*9 is not valid
```

In this function, if user does not give the second parameter b, it assumes it to be 10, but providing the first parameter is necessary.

### 5. Python Function Unknown Number of Parameters

NOTE: If there are, say 4 parameters in a function and a default value is defined for the 2nd one, then 3rd and 4th parameter should also be assigned a default value.

If the number of parameters a function should expect is unknown, then *args is added to the function definition as one of the parameters. This parameter expects a tuple. The asterisk(*) is important here. The name args is just a convention. It can be given any other name.

```def calculate_sum(a, *args):
sum = a
for i in args:
sum += i
return sum

calculate_sum(10) # 10
calculate_sum(10, 11, 12) # 33
calculate_sum(1, 2, 94, 6, 2, 8, 9, 20, 43, 2) # 187
```

Similarly, **kwargs expects a dictionary as parameter.

```def print_names(f1, l1, **kwargs):
print(f1, l1, end=' ')
for key in kwargs:
print(key, kwargs[key], end=' ')

print_names("anish", "gupta")
print_names("anish", "gupta", mohan="singh", mohit="jain")
# anish gupta anish gupta mohan singh mohit jain
```

The above code snippet has reference to for loop. Refer to this for more details: 12 Essential Python For Loop Command Examples

### 6. Python Function Return Value

Python allows function to return multiple values.

```def prime_numbers(x):
l=[]
for i in range(x+1):
if checkPrime(i):
l.append(i)
return len(l), l

no_of_primes, primes_list = prime_numbers(100)
```

Here two values are being returned. When this function is called, the return values are stored in two variables, simultaneously.

NOTE: If a function does not return anything, it implicitly returns None.

### 7. Datatype for Parameters and Return Value

Defining data types for function parameters and the return value can be used to let user know the expectations of the functions.

```def prime_numbers(x:int) -> (int, list):
l=[]
for i in range(x+1):
if checkPrime(i):
l.append(i)
return len(l), l
```

The function definition indicates that it needs one parameter of type int and will return two values of type int and list respectively.