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    
/*ou		window.dataLayer = window.dataLayer || [];
							function gtag(){dataLayer.push(arguments);}
							gtag('js', new Date());

							gtag('config', 'UA-109980514-1');