A function is a block of reusable code that is used to perform a particular task. Functions are used to keep repeated tasks, and a function call is made when you want to perform the same task.
Functions also help reduce the length of your code and prevent
Functions are grouped into three categories:
Built-in functions are already defined in a programming language and you don’t need to write them in order to call them. Python built-in functions are easily recognized by a word followed by parentheses.
Examples of built-in functions include:
print()
(one of the most used functions)len()
str()
int()
title()
A user-defined function is a function that the user of the program writes on their own. The user gives the function any name they want and defines what the function does.
We use the def
keyword followed by the name of the function to create a user-defined function. A user-defined function can be with or without parameter(s).
User-defined functions follow the syntax below:
#function definition
def function_name(parameter1, parameter2,.....):
statement_1
statement_2
# function call
function_name(argument1, argument2, ......)
Parameters are optional in some cases.
# function without parameterdef say_hi():'''this function returns a greeting'''print('Hello user')say_hi()
Let’s say I want to thank everyone who reads my article. It’s too hectic to type the same sentence with different names for the number of people who read the article, so I can write a function to thank them instead.
# function with parametername = "John"def appreciate(name):'''this function greets a user adding the name of the user'''print('Hello ' + name.title() + ', thank you for reading my shot.')appreciate(name)
Lambda functions are anonymous, meaning they are functions without names, unlike user-defined functions, where the function name follows immediately after the def
keyword.
The syntax for a Lambda function is as follows:
lambda argument: expression
You write the lambda
keyword to tell Python that you are writing a Lambda function. Lambda functions are used to carry out a simple operation in a program.
For example, let’s say you have to square every element(number) in a list.
def squares(numbers):'''a function to find the square of numbers'''square = []for number in numbers:square.append(number**2)print(square)squares([1, 5, 4, 6, 8, 11, 3, 12])
Since you are only squaring the elements in one list and not repeatedly, a Lambda function is an efficient option.
numbers = [1, 5, 4, 6, 8, 11, 3, 12]squares = list(map(lambda x: x ** 2, numbers))print(squares)