Dr. R.
Anil Kumar, Associate Professor
UNIT – 4
FUNCTIONS
Syllabus: Defining Functions, Calling Functions
Passing Arguments, Keyword Arguments, Variable-length arguments
Anonymous Functions, Fruitful Functions(Function Returning Values)
Scope of the Variables in a Function - Global and Local Variables.
Defining Functions
A function is a block of code that performs a specific task. A function is a block of
code that takes in some data and, either performs some kind of transformation and returns the
transformed data, or performs some tasks on the data, or both. Functions are useful because
they provide a high degree of modularity. Similar code can be easily grouped into functions.
Functions are the simplest, and, sometimes the most useful, tool for writing modular code.
Types of function
Standard library functions - These are built-in functions in Python that are available to use.
User-defined functions - We can create our own functions based on our requirements.
How to create a function:
1. Function blocks begin with the keyword def followed by the function name and
parentheses ( ).
2. Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
3. The code block within every function starts with a colon (:) and is indented.
4. The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return None.
The following function takes a string as input parameter and prints it on standard screen.
def my_function():
print("Hello from a function")
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code. Once the basic structure of a
function is finalized, you can execute it by calling it from another function or directly from
the Python prompt.
def my_function():
print("Hello from a function")
my_function() # Calling a Function
Python return statement
A return statement is used to end the execution of the function call and “returns” the result
(value of the expression following the return keyword) to the caller. The statements after the
return statements are not executed. If the return statement is without any expression, then the
special value None is returned. A return statement is overall used to invoke a function so that
the passed statements can be executed
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Passing Arguments
Information can be passed into functions as arguments. Arguments are specified after
the function name, inside the parentheses. You can add as many arguments as you want, just
Dr. R. Anil Kumar, Associate Professor
separate them with a comma. The following example has a function with one argument
(fname). When the function is called, we pass along a first name, which is used inside the
function to print the full name:
def my_function(fname):
print(fname + " albert")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
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.
Number of Arguments
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.
def sum1(num1,num2):
sum1=num1+num2
print("the sum is: ", sum1)
sum1(5,9)
Variable-length arguments (Arbitrary Arguments)
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 my_function(*kids):
print("The youngest child is " + kids[2])
my_function("arun", "Tarun", "Lalit")
Keyword Arguments
You can also send arguments with the key = value syntax. This way the order of the
arguments does not matter.
def myfunction(child3, child2, child1):
print("The youngest child is " + child3)
myfunction(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
Arbitrary Keyword Arguments
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 my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Arun", lname = "Kumar")
Anonymous Functions
Python Lambda Functions are anonymous function means that the function is without
a name. As we already know that the def keyword is used to define a normal function in
Python. Similarly, the lambda keyword is used to define an anonymous function in Python.
Syntax: lambda arguments: expression
This function can have any number of arguments but only one expression, which is
evaluated and returned.
x = lambda a, b : a * b
print(x(5, 6))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Dr. R. Anil Kumar, Associate Professor
# To write a function that always doubles the number you send in
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
# Finding the area of a triangle
triangle = lambda m,n : 1/2 * m * n
res=triangle(34,24)
print("Area of the triangle: ",res)
series = [23,45,57,39,1,3,95,3,8,85]
result = filter (lambda m: m > 29, series)
print('All the numbers greater than 29 in the series are :',list(result))
Fruitful functions
Python provides various functions which may or may not return value. The function
which returns any value are called as fruitful function. The function which does not return
any value are called as void function. Fruitful functions mean the function that gives result or
return values after execution. Some functions get executed but doesn’t return any value.
While writing fruitful functions we except a return value and so we must assign it to a
variable to hold return value.
def product(a,b):
c=a*b
return (c)
y=product(5,2)
print("product is",y)
Recursive Functions
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function
calls itself. This has the benefit of meaning that you can loop through data to reach a result.
Recursion as it can be quite easy to slip into writing a function which never terminates, or
one that uses excess amounts of memory or processor power. However, when written
correctly recursion can be a very efficient and mathematically-elegant approach to
programming.
Example
Find Factorial of Number Using Recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# take input from the user
num = int(input("Enter a number: "))
# check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))
Dr. R. Anil Kumar, Associate Professor
Scope of Variables in a Function
A variable is only available from inside the region it is created. This is called scope.
A variable created inside a function belongs to the local scope of that function, and can only
be used inside that function.
def myfunc():
x = 300
print(x)
myfunc()
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
A variable created in the main body of the Python code is a global variable and belongs to the
global scope. Global variables are available from within any scope, global and local.
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Dr. R. Anil Kumar, Associate Professor
Differentiate the function, fruitful function and anonymous functions with example each
Type of Function Definition and Description Example Program
Function A block of reusable code that performs a specific task. Defined using the def keyword. Can def add_numbers(x, y):
take parameters and return a value. return x + y
A function is a block of reusable code that performs a specific task. result = add_numbers(3, 4)
It is defined using the def keyword in Python (or similar keywords in other print(result)
programming languages). # Output: 7
It can take parameters and return a value.
Fruitful function A function that returns a value. Produces some result or output that can be utilized in the def square(x):
rest of the program. Often includes a return statement. return x ** 2
A fruitful function is a type of function that returns a value. result = square(5)
It produces some result or output that can be utilized in the rest of the program. print(result)
Fruitful functions often include a return statement to send back a value. # Output: 25
Anonymous functions Also known as Lambda Function. A function without a name. Defined using the lambda add = lambda x, y: x + y
keyword. Often used for short-term or specific operations. Can take any number of result = add(3, 4)
arguments and have only one expression. print(result)
An anonymous function, also known as a lambda function, is a function without a # Output: 7
name.
It is defined using the lambda keyword and is often used for short-term or specific
operations.
Lambda functions can take any number of arguments but can only have one expression.