Python – Function

A function is a group of related statements or commands that performs a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. It avoids repetition and makes the code reusable. It only runs when it is called.

Syntax

def function_name(parameters):
    statements

You can pass data, known as parameters, into a function. The terms parameter and argument can be used for the same thing: information that are passed into a function. A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called. By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

A function can return data as a result.

def function_name(parameters):
    statements
    return value;

Arbitrary Arguments with *args

If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly

def print_profile(*profile):
    print(f'name: {profile[0]}, age: {profile[1]}')

print_profile("Folau", 30)

You can also send arguments with the key = value syntax. This way the order of the arguments does not matter.

def say_hi(name):
    print(f'Hi {name}')

say_hi(name="Folau")

Arbitrary Keyword Arguments with **

If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition. This way the function will receive a dictionary of arguments, and can access the items accordingly

def print_user(**user):
    print(f'name: {user["name"]}, age: {user["age"]}')

 

How to call a function?

Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function, use the function name followed by parenthesis

def say_hi(name):
    print(f'hi {name}')

say_hi('Folau')

The pass statement

function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.

def say_hi():
   pass

 

Lambda

Lambda is an anonymous function that is defined without a name. Lambda functions are defined using the lambda keyword. A lambda function can take any number of arguments, but can only have one expression.

Syntax

lambda arguments: expression

The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.

doubleNumber = lambda num : num * 2

multiply = lambda num1, num2 : num1 * num2


# Lambda function
doubledNum = doubleNumber(3);
print(doubledNum) # 6

# Lambda function
result = multiply(3,3);
print(result)# 9

Uses of Lambda

We use lambda functions when we require a nameless function for a short period of time. We generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter()map() etc.

numbers = [1,2,3,4,5,6]
new_numbers = list(filter(lambda x: (x%2==0), numbers))
print(f'{new_numbers}') #[2, 4, 6]

 

Module

Modules refer to a file containing Python statements and definitions. A file containing Python code, for example: user.py, is called a module, and its module name would be user. We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code. We can define our most used functions in a module and import it, instead of copying their definitions into different programs.

How to use a module?

We can import the definitions inside a module to another module or the interactive interpreter in Python. We use the import keyword to do this. To import our previously defined module user, we type the following in the Python prompt. Using the module name we can access the function using the dot . operator

import user

user.say_hi()

Python has tons of standard modules. You can check out the full list of Python standard modules and their use cases. These files are in the Lib directory inside the location where you installed Python.

Import but rename or give it alias

import user as u

from module import statement

# just one function
from user import say_hi

# import all functions
from user import *

Source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *