Functions in Python

A function is a group of statements; Functions can be called again and again to perform a particular task without making the code duplication.

The function reduces the duplication of code and decomposes a complex problem into a number of simple problems.

The advantages of functions are :

  • Functions help to decompose a massive program into a small program and easy to maintain and debug easily.
  • Programmers working on a large project can divide the workload by making different functions
  • It helps in code reusability.

There two types of functions are :

  • A Function that readily comes with python is called built-in features.
    Example:
    print("Hello")
    ## print() is a built-in function present in python
    id()
    print()
    type()
    input()
    eval()​
  • A Function that is defined by ourself to perform a specific task is called as user-defined functions.
    Example:
def calculate(a,b):
      print('The Sum:', a+b)
      print('The Difference:', a-b)
      print('The Product:', a*b)
calculate(50,40)      

The output is:

calculate-program-one

In the case of repeated code, we can write the function only once and can call any number of times.

def calculate(a,b):
      print('The Sum:', a+b)
      print('The Difference:', a-b)
      print('The Product:', a*b)
calculate(22,3)
calculate(30,23)
calculate(40,20) 

The output is:

calculate-program-two

Write a function to print wish() Function.

def wish():
       print("Hello Friends happy independence day....!!!")
wish()

The output is:

wish-function-program

History of Python

Function Parameters in Python

A function can take a parameter; these parameters act as an input to the function while calling a function. The parameters could be a value of any datatype. We have to provide some values to the parameter; otherwise, python will throw a type error.

The syntax for the function parameter is:

def function_name(parameters)

Example:

A function to take the name of the student as a parameter and print wish message by name.

def wish(name):
       print("Hello", name, "Good Morning")
wish("Ashu")

The output is:

wish-message-by-name

While calling a function, if the function has a parameter, then we have to provide the values to the parameter; otherwise, python will throw a type error.

def wish(name):
       print("Hello", name, "Good Morning")
wish()

##The output is:

  File "C:/Users/User/.spyder-py3/temp.py", line 3, in <module>
    wish()

TypeError: wish() missing 1 required positional argument: 'name'

The output is:

type-error

A function to take a number as its parameter and print its square value

def squareit(num):
    result=num*num
    print("The square of {} is: {}".format(num,result))
squareit(3)

The output is:

square-of-number

Installation Of Python

Return Statements in Function

The return statement causes your function to exit the current function and hand back value to its caller. The point of functions, in general, is to take inputs and return something. The return statement should be present at the end of the function.

It is not necessary that all the return statements will return some value.

The syntax for the return statement is :

def greater_than_1(n):
 return n > 1
print(greater_than_1(1))
print(greater_than_1(2))

The output is:

return-statement-is-holded

The following example demonstrates the return statement with return type as int.

def add(a,b):
    sum=a+b
    return sum
result=add(20,30)
print("The Sum:",result)
print("The Sum:",add(200,300))

The output is:

demo-program-of-return-statement

Python returns None when no return value is specified

def no_expression_list():
  return    # No return expression list.
print(no_expression_list())

The output is:

return-statement-is-not-holded

The default Return value of Function is None

Write a function to find the factorial of a given positive int value

def factorial(num):
    result=1
    while num>=1:
        result=result*num
        num=num-1
        return result
    
print("The factorial of 3 is:", factorial(3))
print("The factorial of 5 is:",factorial(5)

The output is:

finding-the-factorial-of-positive-number

The following example demonstrates returning multiple values from the function

def sum_sub(a,b):
    sum=a+b
    sub=a-b
    return sum,sub
x,y=sum_sub(30,20)
print("The Sum:", x)
print("The Subtraction:", y)

The output is:

sum-and-subtraction-of-numbers

The following example illustrates how a python function returns multiple values by using the tuple concept internally.

def calc(a,b):
    sum=a+b
    sub=a-b
    mul=a*b
    div=a/b
    return sum,sub,mul,div
t=calc(40,30)
print(type(t))
print("The results are:")
for x in t:
    print(x) 

The output is:

printing-multiple-values

Python Interfaces

Different Types of Arguments in Functions

The argument is the actual value of any variable which is getting passed to the function. The Variable is defined by a method, and that receives the value when the method is called.

The syntax is:

def function(a,b): ##a,b==> Parameter/Variables
       print(a,b)

function(10,20) ##10,20==>Arguments

There are Four Types of Arguments in Python

Introduction to Python Datatypes

Positional Arguments in Python Function

The Positional Argument represents the position of an argument, or The argument which is passing to the function in the correct positional order is called a positional argument.

In positional arguments, the order is important; if we change the order, then it will impact on the result.

The following example demonstrates the positional argument.

def sub(a,b):
    print(a-b)
    
sub(200,100)

The output is:

positional-argument-python

If we change the order of the arguments

def sub(a,b):
    print(a-b)
    
sub(100,200)

The output is:

chanhing-parameter-order

If we pass only one argument, then we will get a type error

def sub(a,b):
    print(a-b)
    
sub(200)

The output is:

type-error-passing-only-one-argument

Exception Handing in Python

Keyword Arguments with Functions in Python

When we are passing arguments to a function, we can mention their name and then specify their values, these kinds of arguments are called keyword arguments.

In the case of keyword arguments, we can pass the argument values by specifying the keyword, and hence, the order is not important.

Example:

def sub(a,b):
    print(a-b)

sub(a=200,b=100)
sub(b=100,a=200)

The output is:

keyword-arguments

It is possible to use positional arguments and keyword arguments simultaneously, but first, we have to take the positional arguments and then keyword argument

def sub(a,b):
    print(a-b)

sub(100,b=200)

The output is:

using-positional-and-keyword-arguments-symultainiously

Polymorphism

Default Arguments in Python Functions

Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator

Example : If the function is having any parameter, then at the time of calling the function we have to assign the value to it.

def wish(name):
      print("Hello",name, "best wishes...!!")
wish("Ashu")

The output is:

assigning-value-to-the-parameter

If we do not assign a value to the parameter at the time of calling the function then, python will throw an error.

def wish(name):
      print("Hello",name, "best wishes...!!")
wish()

The output is:

without-passing-the-parameter

So to overcome this error, we can declare the parameter with the default argument/value

def wish(name="guest"):
      print("Hello",name, "best wishes...!!")
wish()

The output is:

considering-the-default-value

If we pass the argument value explicitly, then python won't consider the default value; instead, it will consider the value that we passed.

def wish(name="guest"):
      print("Hello",name, "best wishes...!!")
wish("Harush")

The output is:

considering-the-explicit-value

Consider the below examples :

1. Both the arguments not having a default value; hence, you have to compulsory assign the values at the time of calling a function.

def wish(name,msg):
      pass

2. Both the arguments are assigned with the default values and thus if the user does not assign any values, then python will consider default values only.

def wish(name="Guest", msg="Good  morning"):
      print("Helllo",name,msg)
    
wish()

The output is:

both-the-arguments-are-default-arguments

3. The below example contains two arguments, in that the first argument as the non-default value and the second argument is the default value and hence, at the time of calling the function, the user has to provide value to the first argument and the second one is optional.

def wish(name, msg="Good  morning"):
    print("Helllo",name,msg)
    
wish("Radha")

The output is:

first-argument-is-default-argument

4. The below example contains two arguments, in that the first argument is the default value and the second argument is the non-default value, python does not support to use non-default value as a second argument, and hence the below code is invalid.

def wish(name="Raj",msg):
    print("Hello",name,"Good evening")
    
wish()

The output is:

second-argument-is-non-deafault-argument

Python Static Variables

Nested Function

Declaring a function inside another function is called a nested function.

The following example demonstrates the nested function

def outer():
    print("outer function execution started")
    
    def inner():
        print("Inner function execution")
        
    inner()
    print("outer function execution completed")
outer()    

The output is:

nested-function

We can call inner() function any number of times.

def outer():
    print("outer function execution started")
    
    def inner():
        print("Inner function execution")
        
    inner()
    inner()
    inner()
    inner()
    print("outer function execution completed")
outer()    

The output is:

calling-inner-function-any-number-of-times
We cannot call the inner function outside the outer() function if we try to call the inner function outside the outer() function then we will get name error.

def outer():
    print("outer function execution started")
    
    def inner():
        print("Inner function execution")
        
    print("outer function execution completed")  
outer() 
inner()   ##calling inner function outside outer() function

The output is:

naming-error-calling-inner-function-outside-the-outer-function

Nested List in Python

A Function as a return value or A Function as an Argument to the Function

A function can return another function and which can be assigned to the new reference variable, and when we call that new reference variable, the return function will execute.

The following example demonstrates function returns another function as a return value

def outer():
    def inner():
        print("Inner function execution")
    return inner    
/*outer function will be executed and returns the inner function as a return value, for the return function object we are assigning new reference variable function1()*/
function1=outer() 
function1()  

The output is:

function-returns-the-another-function-as-return-value

We can pass a function as an argument to the other function.

Example: map(),reduce()

The following example demonstrates passing a function as an argument to another function.

def function1(func):
    func()
    
def function2():
    print("f2 function")
function1(function2)    

The output is:

function-as-an-argument-to-the-function

The following examples demonstrate the Decorator Function

Example 1:In the below example if we call display() function, then decorator will take display() function as an argument to it and executes the decorator and returns the inner function and the inner function will execute its statements in the output.

def decor(func):  
    def inner():
        print("Executing decorator demo programs")
        print("Decorator is a beautiful concept")
        
    return inner
@decor
def display():
    print("Giving example to the decorator")
    
display()

The output is:

decorator-demo-program

Example 2:

def decor_for_add(func):
    def inner(a,b):
        print("#"*30)
        print("TheSum:",end="")
        func(a,b)
        print("#"*30)
    return inner

@decor_for_add
def add(a,b):
    print(a+b)

add(20,30)          

The output is:

decorator-demo-example

If a decorator is applied on a function, then function and decorator should have same number of arguments

If the decorator contains two arguments then the main function add() should also contain two arguments only, if the main function contains more than two arguments, then we will get a type error.

def decor_for_add(func):
    def inner(a,b,c):  #inner function conatining three arguments 
        print("#"*30)
        print("TheSum:",end="")
        func(a,b)
        print("#"*30)
    return inner

@decor_for_add
def add(a,b):
    print(a+b)

add(20,30)          

The output is:
File "C:/Users/User/.spyder-py3/testt.py", line 13, in <module>
    add(20,30)

TypeError: inner() missing 1 required positional argument: 'c'

Example 3:

def decor(func):
    def inner(name):
        names=["CM","PM","Minister"]
        if name in names:
            print("#"*50)
            print("Hello {} you are very important for us".format(name))
            print("very very goof Morning..!!")
            print("#"*50)
        else:
            func(name)
    return inner

@decor
def wish(name):
    print("Good Morning:",name)
wish("Minister")        

When we call wish() function with normal values which are not listed in the names list, the output is:

calling-wish-function-with-normal-narmal-names

When we call wish() function with the values which are present in the list, the output is:

wish-message-with-cm-pm-minister

Example 4:

def smart_division(func):
    def inner(a,b):
        if b==0:
            print("Hello, we cannot divide by Zero")
        else:
            func(a,b)
    return inner

@smart_division
def division(a,b):
    print(a/b)

division(10,3)
division(10,0)        

The output is:

decorator-for-zero-division-error

Decorator function should be defined first and then used

The following example demonstrates the calling same function with and without a decorator

def decor(func):
    def inner(name):
        if name=="Tarun":
            print("#"*30)
            print("Hello Tarun, you are very important for us..!!")
            print("Very Very Good Morning..!!")
            print("#"*30)
        else:
            func(name)
    return inner
def wish(name):
    print("Good Morning:",name)
decorated_wish=decor(wish)
decorated_wish("Revathi")        

The output is: calling a function with decorator

output-of-function-with-decorator

The output is: Calling a function without the decorator.

calling-function-without-decorator

Finally, Block in python

Variable Length Arguments in Python Functions

We can declare an argument that can accept any number of arguments is called variable-length arguments.

The syntax for the variable-length argument is:

def function(*number):  ##*number==>variable length arguments

Example:

def function(*number):
      print("Variable Length Arguments Function") 
function()
function(1,2)
function(3,4,5,6)

The output is:

variable-length-arguments
The following example demonstrates the variable-length arguments

def sum(*number):
    total=0
    for x in number:
        total=total+x
    print("The sum:", total)

sum()    
sum(10)
sum(10,20)
sum(20,30,40)

The output is:

variable-length-argument-python

If we pass the arguments as shown below then the x will contain a single value and y will individually become a Tuple.

def function(x,*y):
      print(x)
      print(y)
function(10,20,30,40)

The output is:

passing-two-variables-one-with-tuple

If pass the two arguments x and y then calling only one value x and then the second value y will become empty Tuple.

def function(x,*y):
       print(x)
       print(y)
function(x)

The output is:

creating-empty-tuple
If we take the x as a variable-length argument and y as single value then python will throw an error

def function(*x,y):
      print(x)
      print(y)
function(10,20,30,40)

The output is:

for-x%20as-variable-length-argument
To overcome this error, we can represent the arguments as below

def function(*x,y):
      print(x)
      print(y)
function(10,20,30,y=40)
When we use the first argument as a variable-length argument and second argument as a normal argument, at the time of calling the normal argument we have to provide value to the normal argument by using keyword argument.

The output is:

assign-value-to-the-normal-argument-by-using-keyword-argument
Python will throw a syntax error when we try to have a function that accepts more than one variable-length argument.

def function(*x,*y):
      print(x)
      print(y)
function(10,20,30,40)

The output is:

using-two-variable-length-arguments

The important conclusions about the arguments are:

After the variable-length argument, if we are taking any normal argument then we have to provide values by using the Name for that normal argument.

More than one variable-length arguments are not allowed.

The difference between *args and **kwargs
*args **kwargs
This is a variable-length argument This is a variable-length keyword argument
If the function(*n) the by using all the values internally python will create a Tuple. If the function(**kwargs), then we call this function by using any number of keyword arguments, and these key values internally become Dictionary.

Example for *args:

def function(*n):
      print(n)
function()
function(10,)      
function(10,20,30)

The output is:

example-for-args
Example for **kwargs:

def function(**kwargs):
      print(kwargs)
function()
function(name="Shru",rollnum=10)      
function(A=10,B=20,C=30)

The output is:

example-for-kwargs
The following example demonstrates the simultaneous use of variable length argument and variable-length keyword arguments.

def function(*args,**kwargs)
       print(args)
       print(kwargs)
function(10,20,A=30,B=40)

The output is:

using-args-and-kwargs
First, we take keyword argument and then normal argument then python will throw an error.

def function(**kwargs,*args):
       print(args)
       print(kwargs)
function(A=30,B=40,10,20)

The output is:

keyword-argument-and-normal-argument

Super() Function in python

Arguments Case Study

1. The use of variable-length argument and default argument are applicable at the time of defining a function. The use of positional argument and keyword argument is applicable at the time of calling a function.

But we have to consider the positional argument in case of calling a function and also after the default argument we cannot use variable-length argument.

def function(arg1,arg2,arg3=5,arg4=15):
       print(arg1,arg2,arg3,arg4)
function(3,2)
function(10,20,30,40)
function(25,50,arg4=100)
function(arg4=3,arg2=1,arg2=5)

The output is:

case-study-one
case:2

def function(arg1,arg2,arg3=5,arg4=15):
       print(arg1,arg2,arg3,arg4)
 /* this will become invalid because there are two positional arguments are there, 
when we have positional arguments compulsary we have to assign 
values at the time of calling a function*/
function( )
#after keyword arguments python won't take positional arguments and hence this function is invalid
function(arg3=10,arg4=20,30,40) 
##here 4 is for arg1 and arg2 is 6 and again we are assigning value to the arg2 as 6 so this will become invalid
function(4,5,arg2=6) 
##the function does not having arg5 argument and hence this argument will become invalid
function(4,5,arg3=5,arg5=6) 

The output for function()

output-for-empty-function
The output of the function(arg3=10,arg4=20,30,40)

positional-argument-follows-keyword-argument
The output of the function(4,5,arg2=6)

functional-argument-got-multiple-arguments
The output of function(4,5,arg3=5,arg5=6)

unexpected-keyword-argument

Variables in Python

Types of Variables in Pythons Functional Programming

In python, variable gives different data to the computer for data processing; the datatypes may be anything like List, Tuple, String, Dictionary, etc...

There are two types of Variables in Python

Global Variables :
  • The Variables which are declared outside of the function are called Global Variables; these variables are nowhere related to the particular function.
  • The Global variable can be accessed from anywhere and in any function based on a python module.
  • We can declare a global variable directly inside the function.

Example:

a=19
def function():
       print(a)
def function1():
      print(a)
function()
function1()

The output is:

global-function

Local Variables:

The Variables which are declared inside a function are called Local Variables. We can access these variables only within the function and not outside of the function.

Example:

def fun():
    b=23
    print(b)
    
def fun1():
    print(b)

fun()
fun1()    

The output is:

local-variable-example
In Python, Global and Local variables can have the same name, but if the function is having both Global and Local variables when we call that function, then it will print the value of the Local variable.

c=25
def fun():
      c=34
      print(c) ##prints Local variable 
def fun1():
       print(c) ##prints Global variable

fun()
fun1()

The output is:

priority-oflocal-variable
To make the Global variable should be available to the function to perform required modifications by using the Global keyword.

c=25
def fun():
 ##by using global keyword approach we made global variable available to the fun() and its value will become 34
    global c
    c=34
    print(c)
      
def fun1():
## the current global value will be 34 and hence python prints 34
       print(c) 

fun()
fun1()

The output is:

global-keyword-approach
consider the below example, in that first function, is having a default local variable, but this variable we cannot access from the second variable, and we can use global keyword to make it a global variable.

def func():
    E=16
    print(E)
func()

The output is:

defining-local-variable
If we try to access Localvariable E from func1(), then Python will throw an error

def func():
    E=16
    print(E)
def func1():
     print(E)
func()
func1()

The output is:

cannot-access-local-variable-from-func1

So to overcome this problem, we can use the global keyword to make it available to access from any other function.

def func():
    global E
    E=16
    print(E)
def func1():
     print(E)
func()
func1()

The output is:

accesssing-local-variable-as-local-variable
We cannot use a global variable before the global declaration; otherwise, we will get a name error

R=234
def func()
     print(R) ## here we are using the global variable before declaring it
     global R
     R=567
     print(R)
func()

The output is:

using-global-variable-before-declaration-error

This space will be replaced Automatically with ads, so do not delete me. Must be inserted only Above H3, H4, H5So, first, we have to declare the global variable then we can use it.
R=234
def func():
     global R
     print(R)
     R=567
     print(R)
func()

The output is:

first-declare-the-global-variable-then-use-it

Characteristics of Variables:

To make Global Variable available to the function, so that we can perform some required modifications

To declare the global variable inside the function explicitly.

Before the global variable, we cannot use any variable.

We cannot use a global variable before the global declaration.

The gobals() the function returns a dictionary that contains all the global variables available to that module.

We can access these available global variables in two ways as follow:

  • globals().get[key]
  • globals()[key]

The following example demonstrates the use of globals() function

In the first case, the function is having both a global variable and a local variable; when we call the function then according to the priority, the function will access the local variable value

a=666
def function():
       a=777
       print(a)
      
function()

The output is:

accessing-the-local-variable
So by using the globals() function, we can make all the global variables available to this module.

a=666
def function():
       a=777
       print(globals().get('a')) ##by using first access method
       print(globals()['a']) ## by using the second access  method
function()

The output is:

accessing-global-variable-by-using-globals-fun

Python Object Oriented Programming Language

Recursive Function

A function that calls itself as a part of the function is called a recursive function.

The advantages of recursive functions are :

We can quickly solve complex functions

The length of the code will be reduced, and hence by default, the readability of the program will be increased.

The following example demonstrates the finding the factorial of n numbers

def factorial(n):
    if n==0:
        result=1
    else:
        result=n*factorial(n-1)
        return result
for i in range(11):
    print("The factorial of {} is:{}".format(i,factorial(i)))

##The out is:
The factorial of 0 is: 1
The factorial of 1 is: 1
The factorial of 2 is: 2
The factorial of 3 is:6
The factorial of 4 is:24
The factorial of 5 is:120
The factorial of 6 is:720
The factorial of 7 is:5040
The factorial of 8 is:40320
The factorial of 9 is:362880
The factorial of 10 is: 3628800
The Depth of the Recursive function:

In python, we can call any function internally almost 995 times. The depth of the recursive function is 955 times.

The following example demonstrates the depth of any recursive function.

count=0
def factorial(n):
    global count
    count=count+1
    print("Executing Factorial function with n value:",n)      
    if n==0:
        result=1
    else:
        result=n*factorial(n-1)
        return result
    print(factorial(3))
    print("The number of times factorial function executes:",count)
    
##The output is:
Executing Factorial function with n value:3
Executing Factorial function with n value:2
Executing Factorial function with n value:1
Executing Factorial function with n value:0
6
The number of times factorial function executes:4

Python Logging

Anonymous Functions or Lambda Functions

A function without any name is called an anonymous function. The anonymous functions are defined by using the Lambda keyword.

The following example demonstrates the use of Anonymous function

function=lambda n:n*n
for i in range(1,11):
    print("The square of {} is:{}".format(i,function(i)))

The output is:

use-of-lambda-function
The following example illustrates the use of the lambda function to find the sum of two given numbers.

info=lambda a,b:a+b
print(info(30,40))
print(info(50,70))

The output is:

sum-of-two-numbers-by-using-lambda-fun
The following example demonstrates the use of lambda function to find the most significant number from the given numbers

bigger=lambda a,b,c:a if a>b and a>c else b if b>c else c
print(bigger(10,30,50))
print(bigger(0,6,8))
print(bigger(-4,-6,-10))

The output is:

finding-the-biggest-number-using-lambda-fun

Installation of Python Package

A Function as an Argument to Another Function

A function can be passed as an argument to another function

Example: We have three types of such functions

We can use filter() function to filter values from the given sequence based on some condition
The syntax for the filter() function is:

filter(function,equence)​

The following example demonstrates the use of filter() function.

List=[0,1,2,3,4,5,6,7,8,9,10] ##here i want to print only the even numbers from the list by using the filter() function
def isEven(n):
    if n%2==0:     ##isEven is a function which will be using in the filter function with list as a sequence to it
        return True
    else:
        return False
List1=list(filter(isEven,List)) ##filter function i always an object so we need to convert it into a list beofre print the output 
print(List1)  

The output is:

finding-the-even-number-by-using-filter-fun

The above program can also be executed by using the lambda() function

List=[0,1,2,3,4,5,6,7,8,9,10]
List1=list(filter(lambda n:n%2==0,List))
print(List1)

The output is:

finding-even-number-by-using-labda-fun

In the same way, we can filter odd numbers from the given list by using filter() function a lambda function.

List=[0,1,2,3,4,5,6,7,8,9,10]
List1=list(filter(lambda n:n%2!=0,List))
print(List1)

The output is:

filtering-oadd-numbers

The following example demonstrates the filtring of fruits name starts with p letter

Fruits=["Apple","Orange","Pomegranate","Papaya","Plum"]
info=list(filter(lambda name:name[0]=='P', Fruits))
print(Fruits)

The output is:

filteing-fruits-starts-with-letter-p

map() function:

By using the map() function for every element present in the sequence we can apply some functionality and generate new elements with the required modification.

The function can be applied to each element of the sequence and generates a new series.

The syntax for the map() function is:

map(function,sequence)​

The following example demonstrates the map() function

info=[1,2,3,4,5,6,7,8,9,10]
info1=[5,15,20,25,30]
info3=list(map(lambda x,y: x*y, info,info1))
print(info3)

The output is:

output-of-map-function

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions