What is Python function?

In Python, a function is a group of related statements that performs a specific task. A function can be defined as the organized block of reusable code, which can be called whenever required. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.

Python allows us to divide a large program into the basic building blocks known as a function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the Python program. The Function helps to programmer to break the program into the smaller part. It organizes the code very effectively and avoids the repetition of the code. As the program grows, function makes the program more organized.

File name : index.py

There are mainly two types of functions.

  • User-define functions - The user-defined functions are those define by the user to perform the specific task.
  • Built-in functions - The built-in functions are those functions that are pre-defined in Python.

  • Advantage of Functions

    File name : index.py

    There are the following advantages of Python functions.

  • Using functions, we can avoid rewriting the same logic/code again and again in a program.
  • We can call Python functions multiple times in a program and anywhere in a program.
  • We can track a large Python program easily when it is divided into multiple functions.
  • Reusability is the main achievement of Python functions.
  • However, Function calling is always overhead in a Python program.

  • Howt to create function in python?

    In Python, def keyword us used to define the function.

    File name : index.py

    Syntax

    def my_function(parameters):
        function_block
    return expression

  • A function accepts the parameter (argument), and they can be optional.
  • The function block is started with the colon (:), and block statements must be at the same indentation.
  • A colon (:) to mark the end of the function header.
  • The return statement is used to return the value. A function can have only one return

  • How to call Function in Python?

    In Python, A function must be defined before the function call; otherwise, the Python interpreter gives an error. To call the function, use the function name followed by the parentheses.

    File name : index.py

    #function definition

    def itechxpert():
        print("hello sana")

    # function calling

    itechxpert()

    return statement in python

    The return statement is used at the end of the function and returns the result of the function. It terminates the function execution and transfers the result where the function is called. The return statement cannot be used outside of the function.

    File name : index.py

    return [expression_list]

    It can contain the expression which gets evaluated and value is returned to the caller function. If the return statement has no expression or does not exist itself in the function then it returns the None object.

    File name : index.py

    # Defining function

    def sum():
         a = 10
         b = 20
         c = a+b
         return c

    print("The sum is:",sum())

    Arguments in function in python

    The arguments are types of information which can be passed into the function. The arguments are specified in the parentheses. We can pass any number of arguments, but they must be separate them with a comma.

    File name : index.py

    def Dob (name):
        print("DOB :7th May,2020",name)

    Dob("sana")

    Example

    File name : index.py

    # Add Two Numbers
    def sum (a,b):
        return a+b;

    #taking values from the user

    a = int(input("Enter a: "))
    b = int(input("Enter b: "))

    print("Sum = ",sum(a,b))

    File name : index.py


    Call by reference

    In Python, call by reference means passing the actual value as an argument in the function. All the functions are called by reference, i.e., all the changes made to the reference inside the function revert back to the original value referred by the reference.

    File name : index.py

    Example 1 Passing Immutable Object (List)


    #defining the function
    def change_list(list1):
         list1.append(20)
         list1.append(30)
         print("list inside function = ",list1)

    #defining the list
    list1 = [10,30,40,50]

    #calling the function
    change_list(list1)
    print("list outside function = ",list1)

    Output :-

    list inside function = [10, 30, 40, 50, 20, 30]
    list outside function = [10, 30, 40, 50, 20, 30]

    Example 2 Passing Mutable Object (String)

    File name : index.py

    #defining the function
    def change_string (str):
         str = str + " How are you "
         print("printing the string inside function :",str)

    string1 = "Hi I am there"

    #calling the function
    change_string(string1)

    print("printing the string outside function :",string1)

    Output :-

    printing the string inside function : Hi I am there How are you
    printing the string outside function : Hi I am there

    Types of arguments in Python

    There may be several types of arguments which can be passed at the time of function call.

    File name : index.py

  • Required arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

  • Required Arguments

    we can provide the arguments at the time of the function call. As far as the required arguments are concerned, these are the arguments which are required to be passed at the time of function calling with the exact match of their positions in the function call and function definition. If either of the arguments is not provided in the function call, or the position of the arguments is changed, the Python interpreter will show the error.

    File name : index.py

    def showname(name):
        msg = "Hello "+name
        return msg
    name = input("Enter the name:")
    print(showname(name))

    Default Arguments

    Python allows us to initialize the arguments at the function definition. If the value of any of the arguments is not provided at the time of function call, then that argument can be initialized with the value given in the definition even if the argument is not specified at the function call.

    File name : index.py

    def printme(name,age=1):
        print("My name is",name,"and age is",age)
    printme(name = "sana")

    Variable-length Arguments (*args)

    In large projects, sometimes we may not know the number of arguments to be passed in advance. In such cases, Python provides us the flexibility to offer the comma-separated values which are internally treated as tuples at the function call. By using the variable-length arguments, we can pass any number of arguments. However, at the function definition, we define the variable-length argument using the *args (star) as *.

    File name : index.py

    def printme(*names):
        print("type of passed argument is ",type(names))
        print("printing the passed arguments...")
        for name in names:
        print(name)
    printme("Mahtab","Habib","Sana","Sara")

    Keyword arguments(**kwargs)

    Python allows us to call the function with the keyword arguments. This kind of function call will enable us to pass the arguments in the random order. The name of the arguments is treated as the keywords and matched in the function calling and definition. If the same match is found, the values of the arguments are copied in the function definition.

    File name : index.py

    #function func is called with the name and message as the keyword arguments
    def func(name,message):
        print("printing the message with",name,"and ",message)

    #name and message is copied with the values John and hello respectively
        func(name = "John",message="hello")





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here