Functions
Functions
Functions:
In Python, a function is a group of related statements 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.
Furthermore, it avoids repetition and makes the code reusable.
Syntax def function_name(parameters):
"""docstring"""
statement(s)
Keyword def that marks the start of the function header.
A function name to uniquely identify the function. Function naming follows the same rules
of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of the function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid python statements that make up the function body. Statements must have
the same indentation level.
An optional return statement to return a value from the function.
Example function
def greet(name):
""" This function greets to the person
passed in as a parameter ”””
print("Hello, " + name + ". Good morning!")
Once we have defined a function, we can call it from another function, program or even the
Python prompt.
To call a function we simply type the function name with appropriate parameters.
greet(‘John') # function call
Hello, John. Good morning! #output
return statement
Syntax:
return [expression_list]
This statement can contain an expression that gets evaluated and the value is returned. If
there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.
print(greet("May")) #fun call
Hello, May. Good morning! #output
None #output
Example:
def absolute_value(num):
"""This function returns the absolute value of the entered number """
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
#output
2
4
Calling Function:
• A function definition specifies what a function can do, but it does not cause the function to
execute.
• To execute a function, you must call it. This is how we would call the “add(x,y)” function:
add(1,25) #function call
• When a function is called, the interpreter jumps to that function definition and executes the
statements in its body.
• Then, when the end of the body is reached, the interpreter jumps back to the part of the
program that called the function, and the program resumes execution at that point. When this
happens, we say that the function returns
Example:
def add(x,y): #function definition
s=0
for i in range(x,y+1):
s=s+i
print('sum of numbers from',x,' to',y,s)
#function calling
add(1,25). # here 1,25 are called Actual Parameters
Function Arguments:
An argument is any piece of data that is passed into a function when the function is called.
This argument is copied to the argument in the function definition.
The arguments that are in the function call are known as “Actual Arguments or Parameters”.
The arguments that are in function definition are called “Formal arguments or Parameters”.
We can pass one or more number of actual arguments in the function call. The formal
argument list and their type must match with actual arguments.
Until now, functions had a fixed number of arguments. In Python, there are other ways to
define a function that can take variable number of arguments.
Three different forms of this type are described below
Default Arguments:
• Python allows functions to be called without or with less number of arguments than that are
defined in the function definition.
• If we define a function with three arguments and call that function with two arguments,
then the third argument is considered from the default arguments.
• The default value to an argument is provided using the assignment (=) operator.
• If the same number of arguments are passed then the default arguments are not considered,
the formal arguments are overwritten by the actual arguments.
def greet(name, msg="Good morning!"):
print("Hello", name + ', ' + msg)
greet("Kate")
greet("Bruce", "How do you do?")
#output
Hello Kate, Good morning!
Hello Bruce, How do you do?
Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.
Non-default arguments cannot follow default arguments.
def greet(msg = "Good morning!", name)
Syntax Error: non-default argument follows default argument
Keyword Arguments:
When we call a function with some values, these values are passed to the formal
arguments in the function definition based on their position (in the order).
Python also allows functions to be called using the keyword arguments in which the
position (order) of the arguments can be changed.
The values are not copied according to their position, but based on their names.
The actual arguments in the function call can be written as follow:
function_name(Arg_name1=value1,Arg_name2=value2)
An argument that is written according to this syntax is known as “Keyword Argument” .
# 2 keyword arguments
greet(name = "Bruce",msg = "How do you do?")
# 2 keyword arguments (out of order)
greet(msg = "How do you do?",name = "Bruce")
#1 positional, 1 keyword argument
greet("Bruce", msg = "How do you do?")
As we can see, we can mix positional arguments with keyword arguments during a
function call. But we must keep in mind that keyword arguments must follow positional
arguments.
Variable-length arguments:
• In some situations, it is not known in advance how many number of arguments have to be
passed to the function.
• In such cases, Python allows programmers to make function calls with arbitrary (or any)
number of arguments.
• When we use arbitrary arguments or variable-length arguments, then the function
definition uses an asterisk ( *) before the formal parameter name.
def greet(*names):
for name in names:
print("Hello", name)
greet("Monica", "Luke", "Steve", "John")
#output
Hello Monica
Hello Luke
Hello Steve
Hello John
Anonymous Functions:
Lambda or anonymous functions are so called because they are not declared as other
functions using the def keyword. Rather, they are declared using the lambda keyword.
Lambda functions are throw-away functions, because they are just used where they have
been created.
Lambda functions contain only a single line. Its syntax will be as follows:
lambda arguments : expression
The arguments are separated by comma and the expression is an arithmetic expression that
uses these arguments. The function can be assigned to a variable to give it a name.
double = lambda x: x * 2
print(double(5))
#output
10
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
#output 22
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
#output 33
Void Function:
Void functions are those that do not return any value after their evaluation is complete.
These types of functions are used when the calculations of the functions are not needed
in the actual program.
These types of functions perform tasks that are crucial to successfully run the program
but do not give a specific value to be used in the program.
Example:
def area(r):
a=3.14*r*r
print("The area of the circle is:",a)
x=int(input("Enter the radius :"))
#calling the function
print(area(x))
Variables that are defined inside a function body have a local scope, and those defined outside
have a global scope. This means that local variables can be accessed only inside the function in
which they are declared, whereas global variables can be accessed throughout the program body
by all functions. When you call a function, the variables declared inside it are brought into
scope.
Example1:
def myfunc():
x = 300 #local scope
print(x)
myfunc()
#output 300
Example2:
# output 5 5
Example3: