What is a function
A function is a named, independent section of Python code that performs a
specific task and optionally returns a value to the calling program.
It(Function) Allow us to group commonly used code into a compact Unit that
can be used repeatedly.
A Function is named:
Each function has a unique name. By using that name in another part of the
program ,you can execute the statements contained in the functions.
This is known as calling the function . A function can be called from within
another function.
A function is independent:
A function can perform its task without interference from or interfering with
other parts of the program.
Advantage of Functions/Why Use Functions
There are many advantages of functions.
1) They break large computing into smaller ones. It means with the help of
Function we modularize the program/problem.
2) Code Reusability / Code optimization/ Increase Reusability
By creating functions in Python, you can call it many times. So we don't need
to write the same code again and again.
It makes the code optimized; we don't need to write much code. It means By
using the functions We avoid code repetition.
Suppose, you have to check 3 numbers (7, 11 and 531) whether it is prime
number or not.
Without using function, you need to write the prime number logic 3 times. So,
there is repetition of code.
But if you use functions, you need to write the logic only once and you can reuse
it several times. It means function avoids the need for redundant programming.
Commonly Used Predefined Functions
Reading Single Value
input() fn takes one input and returns it as string type, If u want to convert in
other type use respective method.
Ex:-
eval() func in Python
The eval() function parses the expression passed to this method and runs
python expression (code) within the program.
Reading Multiple Values
User Defined Functions
We can also create your own functions. These functions are called user-defined
functions.
Ex:
# This demo is for User defined Func
def myFunc():
print("This is My Func")
myFunc()
Ex:
There are four ways to define function
Take Nothing Return Nothing:
Take Something Return Nothing:
Take Nothing Return Something:
Take Nothing Return Something:
Ex:
# This demo is for return kewword
def myFuncWithReturn():
return "I am a Result"
receive=myFuncWithReturn()
print("The Received Value is = ",receive)
Take Something Return Something:
Note:
When Function returns nothing that time it returns None.
Ex:
[NoneDemo.py]
def myFunc():
print("Hello This is MythBreaker")
#Driver code
rec=myFunc()
print(rec,"---",type(rec))
Function(Default arguments)
Default arguments:
A default argument is an argument that assumes a default value if a value
is not provided in the function call for that argument.
Ex:
Ex:
# This demo is for Default Arguments
def printInfo(name, age=35):
print("Name: ", name)
print("Age ", age)
# Now you can call printInfo function
printInfo(name="DD",age=50)
printInfo(name="DD")
Ex:
Ex:
Python Keyword Arguments
When we call a function with some values, these values get assigned to the
arguments according to their position.
Python allows functions to be called using keyword arguments.
When we call functions in this way, the order (position) of the
arguments can be changed
Ex:
def greet(name,msg):
print("Hello",name + ', ' + msg)
#Driver Code
greet(“Dev","Good morning!")
greet(name = “Dev",msg = "How do you do?")
greet(msg="How do you do?" , name = “Dev")
Variable-length Arguments
You may need to process a function for more arguments than you
Specified while defining the function.
These arguments are called variable-length arguments and are not
named in the function definition, unlike required and default
arguments.
Syntax:
def functionname([formal_args,] *var_args_tuple ):
function_suite / function statements
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all
non keyword variable arguments.
This tuple remains empty if no additional arguments are specified during the
function call.
Ex:
#This demo is for Variable Length Argument
def findAverage(*numbers):
print(numbers,type(numbers))
#Driver Code
findAverage(10,20,30)
Ex:
def printValue(arg1,*vartule):
print(arg1)
for v in vartule:
print(v)
printValue(1)
printValue(1,2,3,4)
printValue(1,2,"Three",4.0)
Ex:
#This demo is for variable length arguments
def f1(teachername,*points):
print(teachername,end=' ')
s=0
for x in points:
s=s+x
print("Total Points=",s)
#Driver Code
f1("DD",10,11,20)
f1("Dev",10,11,20,34,3,4)
Ex:
Variable-length Arguments with return keyword
#This demo is for Variable Length Argument
def findAverage(*numbers):
sum=0
for number in numbers:
sum=sum+number
if(len(numbers) !=0):
return sum//len(numbers)
else:
return "There is no numbers For Average"
result=findAverage(10,20,30)
print("Average is ",result)
Variable-length/Keyword Arguments
This is the combination of variable length arguments and
Keyword Arguments.
The return Statement
return, return None, and no return at
all?
Ex:-
def my_func1():
print("Hello World")
return None
def my_func2():
print("Hello World")
return
def my_func3():
print("Hello World")
They all appear to return None. Are there any differences between how the returned value
of these functions behave? Are there any reasons to prefer one versus the other?
On the actual behavior, there is no difference. They all return None and that's it. However,
there is a time and place for all of these.
In the following example, we return person's mother if the person given is a human. If it's
not a human, we return None
def get_mother(person):
if(is_human(person)):
return person.mother
else:
return None
This is used for the same reason as break in loops. The return value
doesn't matter and you only want to exit the whole function.
It's extremely useful in some places, even though you don't need it
that often.
def find_prisoner_with_knife(prisoners):
for prisoner in prisoners:
if "knife" in prisoner.items:
prisoner.move_to_inquisition()
return # no need to check rest of the prisoners nor raise
an alert
raise_alert()
Note:
You should never do var = find_prisoner_with_knife(), since the return value is not
meant to be caught.
In the following example, we set person's mother's name and then the function exits after
completing successfully.
def set_mother(person, mother):
if is_human(person):
person.mother = mother
Note:
You should never do var = set_mother(my_person, my_mother), since the return value is
not meant to be caught.
Scope of Variables
All variables in a program may not be accessible at all locations in
That program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program
Where you can access a particular identifier.
There are two basic scopes of variables in Python
1) Local variables
2) Global variables
Local vs. Global variables
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
Ex (ScopeDemo1.py):
# This demo is related with scope
total=0 # This is a global variable
def sum(a,b):
total=a+b # Here total is local variable
print("The Sum of two number is ",total)
sum(10,20) # Using sum Func
print("The Total is ",total)
For example, we define a variable Money in the global scope.
Within the function, we assign Money a value, therefore Python assumes
Money as a local variable.
However, we accessed the value of the local variable Money before
assigning/setting it, so an UnboundLocalError is the result.
To overcome this problem we use the global keyword
Ex:
Money=2000 #It is a global variable
def AddMoney():
#global Money # Uncomment the following line to fix the code
Money=Money + 1
print(Money) #2000
AddMoney()
print(Money) #2001
anonymous Functions/ lambda Functions
An anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword in Python,
anonymous functions are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.
You can use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in
the form of an expression.
They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires
an expression.
Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and those in the global
namespace.
Syntax:
lambda arguments: expression
or
lambda [arg1 [,arg2,.....argn]]:expression
Ex:
# Python code to illustrate cube of a number
# showing difference between def() and lambda().
def cube(y):
return y*y*y
lambda_cube = lambda y: y*y*y
# using the normally defined function
print(cube(5))
# using the lamda function
print(lambda_cube(5))
Ex:
# This demo is for Anonymous Function
sum=lambda arg1,arg2:arg1+arg2
#Now You Can call sum as a Function
print("The Result is ",sum(10,20))
print("The Result is ",sum(30,20))
Ex:
Ex:
Ex:
# This demo is for Lambda Expression
L =[ lambda x: x**2,
lambda x: x**3,
lambda x: x**4,
]
for f in L:
print(f(3))
#print(L[0](11))
Ex:
print("Please Enter Two Numbers")
maxNumber=(lambda num1,num2:num1 if num1>num2 else num2)
(int(input()),int(input()))
print("Maximum Number is ",maxNumber)
Introduction to map() ,filter() and reduce()
Python provides many built-in functions that are predefined and can
be used by the end-user by just calling them.
These functions not just ease the work of programmers but also
create a standard coding environment.
map(), filter() and reduce() are inbuilt functions of Python. These
functions enable the functional programming aspect of Python.
These functions can take any other function as a parameter and can
be supplied to other functions as parameters as well.
Note:
What is Functional Programming
Functional programming is a programming paradigm in which we try to bind
everything in pure mathematical functions style.
It is a declarative type of programming style. Its main focus is on “what to solve”
in contrast to an imperative style where the main focus is “how to solve”.
It uses expressions instead of statements.
An expression is evaluated to produce a value whereas a statement is executed
to assign variables.
The map() function
This function takes another function as a parameter along with a sequence of iterables and
returns an output after applying the function to each iterable present in the sequence.
SYNTAX:
map(function, iterables)
The map function can take user-defined functions as well as lambda functions as a
parameter.
User-defined functions within map():
The map() function can take user-defined functions as parameters. The parameters of
these functions are exclusively set by the user or the programmer.
Ex:-
def newfunc(a):
return a*a
x = map(newfunc, (1,2,3,4)) #x is the map object
print(x)
print(set(x))
NOTE:
The output is not in order of the values of the iterables because I have used the set() function.
You can also use the list() or tuple() functions
Ex:
def newfunc(a):
return a*a
x = map(newfunc, (1,2,3,4)) #x is the map object
print(x)
print(list(x))
Ex:
def func(a, b):
return a + b
a = map(func, [2, 4, 5], [1,2,3])
print(a)
print(tuple(a))
Using lambda() Function with map()
Lambda functions are functions that do not have any name. These
functions are often supplied as parameters to other functions.
The map() function in Python takes in a function and a list as an argument. The
function is called with a lambda function and a list and a new list is returned
which contains all the lambda modified items returned by that function for
each item.
Ex:
tup= (5, 7, 22, 97, 54, 62, 77, 23, 73, 61)
newtuple = map(lambda x: x+3 , tup)
print(tuple(newtuple))
Ex:
animals = ['dog', 'cat', 'parrot', 'rabbit']
# here we intend to change all animal names to upper case and return the same
uppered_animals = list(map(lambda animal: str.upper(animal), animals))
print(uppered_animals)
The filter() function
The filter() function is used to create an output list consisting of values for which the function
returns true.
SYNTAX:
filter(function, iterables)
Just like map(), this function can be used can also take user-defined functions as
well as lambda functions as a parameter.
Ex
def func(x):
if x>=3:
return x
y = filter(func, (1,2,3,4))
print(y)
print(list(y))
Using lambda() Function with filter()
The filter() function in Python takes in a function and a list as arguments.
This offers an elegant way to filter out all the elements of a sequence
“sequence”, for which the function returns True. Here is a small program
that returns the odd numbers from an input list:
Ex:
# Python code to illustrate filter() with lambda()
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(filter(lambda x: (x%2 != 0) , li))
print(final_list)
Ex:
# code to people above 18 yrs
ages=[13, 90, 17, 59, 21, 60, 5]
adults = list(filter(lambda age: age>18, ages))
print(adults)
The reduce() function
The reduce() function, as the name describes, applies a given
function to the iterables and returns a single value.
SYNTAX:-
reduce(function, iterables)
The function here defines what expression needs to be applied to the
iterables.
This function needs to be imported from the functools module.
Ex:
from functools import reduce
li=[10,20,30,40]
sum = reduce((lambda x, y: x + y), li)
print (sum)
Ex:
from functools import reduce
reduce(lambda a,b: a+b,[47,11,42,13])
Ex:-
#importing functools for reduce()
from functools import reduce
lis=[ 1 , 3, 5, 6, 2]
# using reduce to compute maximum element from list
print ("The maximum element of the list is : ",end="")
print(reduce(lambda a,b : a if a > b else b,lis)
Using map(),filter() and reduce() functions along with each
other
When you do this, the internal functions are first solved and then the outer functions
operate on the output of the internal functions.
Using filter() within map():
The code given below first checks for the condition (x>=3) to be true for the iterables.
Then, the output is mapped using the map() function.
EX:-
c = map(lambda x:x+x,filter(lambda x: (x>=3), (1,2,3,4)))
print(list(c))
OUTPUT: [6, 8]
If you filter out integers greater than or equal to 3 from the given tuple, you get [3,4] as
the result. Then if you map this using(x+x) condition,
you will get [6,8], which is the output.
Using map() within filter():-
When you use the map() function within filter() function, the iterables are first operated
upon by the map function and then the condition of filter() is applied to them.
EX:-
c = filter(lambda x: (x>=3),map(lambda x:x+x, (1,2,3,4))) #lambda x: (x>=3)
print(list(c))
OUTPUT: [4, 6, 8]
Using map() and filter() within reduce():-
The output of the internal functions is reduced according to the condition supplied to the
reduce() function.
Ex:-
from functools import reduce
d = reduce(lambda x,y: x+y,map(lambda x:x+x,filter(lambda x: (x>=3), (1,2,3,4))))
print(d)
OUTPUT: 14
The output is a result of [6,8] which is the result of the internal map() and filter()
functions.