function in python

Functions in Python

Table of Contents

The function in python programming is called a group of that is linked statements that do some specific task. Functions will help to decompose the program into smaller and modular chunks. As the program grows large and larger, the function is going to make more systematic and manageable. It always avoids repetition and makes the code reusable.

The syntax  of function is

     def function_name(parameters):

“””docstring”””

statement

As the above example states that a function consists of the following components

  1. Keyword def will make a start  of the function header
  2. As the function name to uniquely identify the function. The function name follows the same rules of writing identifiers in python.
  3. The parameters or may be the arguments through which we pass values to a function. which are optional
  4. A colon : is to tarck the end of the function header
  5. Optional documentation is a string which explains what the function does
  6. A valid python statements which has the function body statements and has the statements that must have the similar indentation level.
  7. An optional will return statement to return a value from the function.

def greet(name):

     “””

     This function greets to the person passed in as a parameter  “””

     print(“HI, ” + name + “. Good Evening!”)

How we should call the python function?

When we have defined the function we can call it from another function, program, or maybe even a python prompt. To call  a function name with proper parameters like

>>>greet(‘Rakul’)

HI Rakul.Good Evening!

When we try executing the program with the function to see the output.

ef greet(name):

     “””

     This function greets to the person passed in as a parameter “””

    print(“HI, ” + name + “. Good Evening!”)

greet(‘Rakul’)

Docstrings

The first string after the function header is called the docstring and is short for documentation string. The documentation is a good programming practice. Consider the example where we have docstring immediately below the function header. This string will be available to us as the _doc_ attribute of the function.

>>> print(greet.__doc__)

    This function greets to the person passed in as a parameter.

How does the function work?

How function works in Python?

Scope and lifetime of variables:

Scope variables are a part of a program where the variable will be recognized. The parameters and variables defined inside a function are not visible from outside the function. The lifetime will be variable throughout which is a variable that exists in the memory. The lifetime inside a function will be not as long as the function executes. An example is shown below

def my_func():

x = 10

print(“Value inside function:”,x)

x = 30

my_func()

print(“Value outside function:”,x)

Value inside function: 10

Value outside function: 30

The value of x is 30. Where the function my_func() modifies the actual value of x to 10 it will not affect the value outside the function. It is because the variable x inside the function is way different from the one outside. They have the same names where they will be having two different variables with different scopes.

Types of functions

  1. Built-in Functions-Functions that are created to python.

Python_abs() will return value absolute  number.

Python_abs()-An abs() function gives the  actual or absolute value of the given number.If that may be complicated number abs() returns its magnitude.For example

number = -20

absolute_number = abs(number)

print(absolute_number)

# Output: 20

abs() syntax

the abs() syntax method is

abs(num)

abs()parameters

abs() method takes a single argument:

  • num-a number whose absolute value is to be returned.The number will be 

 integer

floating number

complex number

  1. User-defined functions

Functions to which we will be defining ourselves to do certain specific tasks are referred to as user-defined functions. The way in which we define and call function in python is already told.

Advantages are

  1. user-defined functions are supports to break big program to small pieces of segments that makes program quiet simple to understand.
  2. It is repeated code has in a program function that can be used to include those codes and execute when needed by calling that function.

Consider an example

Program to illustrate

# the use of user-defined functions

def add_numbers(x,y):

   sum = x + y

   return sum

num1 = 5

num2 = 6

print(“The sum is”, add_numbers(num1, num2))

output

Enter a number: 2.4

Enter another number: 6.5

The sum is 8.9

Questions

  1. What are Python functions  and its declaration with an example?
  2. Explain the types of functions in Python with an example?

10 Responses

  1. 1) What are Python functions and its declaration with an example?
    A function is a block of code which only runs when it is called.
    We can pass data, known as parameters, into a function.
    A function can return data as a result.

    Python Function Declaration:
    The syntax to declare a function is:
    def function_name(arguments):
    # function body
    return
    Here,
    def – keyword used to declare a function
    function_name – any name given to the function
    arguments – any value passed to function
    return (optional) – returns value from a function

    Let’s see an example,
    def greet():
    print(‘Hello World!’)
    Here, we have created a function named greet(). It simply prints the text Hello World!.

    2) Explain the types of functions in Python with an example?
    1). Built-in Functions:
    Built-in functions are the functions that are already written or defined in python. We only need to remember the names of built-in functions and the parameters used in the functions. As these functions are already defined so we do not need to define these functions. Below are some built-in functions of Python.

    Some of the widely used python built-in functions are:

    Function Description
    len() Returns the length of a python object
    abs() Returns the absolute value of a number
    max() Returns the largest item in a python iterable
    min() Returns the largest item in a python iterable
    sum() Returns the sum of all the items in an iterator
    type() Returns the type of a python object
    help() Executes the python built-in interactive help console
    input() Allows the user to give input
    format() Formats a specified value
    bool() Returns the boolean value of an object

    one example of built-in functions

    #In built functions
    x = [1,2,3,4,5]
    print(len(x)) #it return length of list
    print(type(x)) #it return object type
    Output:
    # 5
    #

    2). User-Defined Functions:
    The functions defined by a programmer to reduce the complexity of big problems and to use that function according to their need. This type of functions is called user-defined functions.
    We can create our own functions based on our requirements.

    #Example of user defined function

    x = 3
    y = 4
    def add():
    print(x+y)
    add()
    Output:
    # 7

  2. 1.What are Python functions and its declaration with an example?
    Python function is a block of statements that return the specific task.The idea is to put some commonly or repeatedly
    done tasks together and make a function so that instead of writing the same code again and again for different inputs,
    we can do the function calls to reuse code contained in it over and over again.
    example: We can create a Python function using the def keyword
    def fun():
    print(” hello world”)
    Calling a Python Function
    After creating a function we can call it by using the name of the function followed by parenthesis containing
    parameters of that particular function.
    example :# A simple Python function
    def fun():
    print(“Welcome to GFG”)
    # Driver code to call a function
    fun()
    out put : welcome to GFG .

    2.Explain the types of functions in Python with an example?
    –There are two types of functions in python:
    a. User-Defined Functions – these types of functions are defined by the user to perform any specific task.to reduce the
    complexity of big problems and use that function according to their need.
    example : def sub(x, y):
    return x-y
    print(sub(5,2))
    output : 3

    b. Built-in Functions – These are pre-defined functions in python. Built-in functions are already defined in python. A
    user has to remember the name and parameters of a particular function. Since these functions are pre-defined,
    there is no need to define them again.
    there are various built in function such as :
    len() Returns the length of a python object
    abs() Returns the absolute value of a number
    max() Returns the largest item in a python iterable
    min() Returns the largest item in a python iterable
    sum() Returns the sum of all the items in an iterator
    type() Returns the type of a python object

    exmaple: l = [2, 5, 19, 7, 43]
    print(“Length of string is”,len(l))
    print(“Maximum number in list is “,max(l))
    print(“Type is”,type(l))

    output : Length of string is 5
    Maximum number in list is 43
    Type is

  3. The function in python programming is called a group of that is linked statements that do some specific task. Functions will help to decompose the program into smaller and modular chunks. As the program grows large and larger, the function is going to make more systematic and manageable. It always avoids repetition and makes the code reusable.

    The syntax of function is

    def function_name(parameters):

    “””docstring”””

    statement
    Keyword def will make a start of the function header
    As the function name to uniquely identify the function. The function name follows the same rules of writing identifiers in python.
    The parameters or may be the arguments through which we pass values to a function. which are optional
    A colon : is to tarck the end of the function header
    Optional documentation is a string which explains what the function does
    A valid python statements which has the function body statements and has the statements that must have the similar indentation level.
    An optional will return statement to return a value from the function.
    def greet(name):

    “””
    This function greets to the person passed in as a parameter “””

    print(“HI, ” + name + “. Good Evening!”)

    greet(‘Rakul’)

    Docstrings

    The first string after the function header is called the docstring and is short for documentation string. The documentation is a good programming practice. Consider the example where we have docstring immediately below the function header. This string will be available to us as the _doc_ attribute of the function.

    >>> print(greet.__doc__)

    This function greets to the person passed in as a parameter.

  4. Functions in Python:

    What are Python functions and its declaration with an example?

    To do some specific task, a group of code is created with linked statements named Functions in Python which
    1. Decomposes the program into smaller and modular chunks.
    2. Makes more systematic and manageable when the program grows larger
    3. Avoids repetition and makes code reusable.

    Declaration of Function:
    The syntax of function is
    def function_name(parameters):
    “””Docstring”””
    Statement
    Example:
    def say(name)
    print(‘Hi + name + H2k welcomes you”)
    def – keyword
    say – function name
    name – parameter
    : – colon ends the function definition
    print – function code
    (‘Hi + name + H2k welcomes you’) – function return statement

    Explain the types of functions in Python with an example?
    Types of functions:
    Built-in Functions-
    Functions that are already created in python. All we should do in python is ‘keep familiar with the syntax and remember its usage’. len(), bool(), list(), int(), input() are some built-in functions.

    Python_abs() will return the absolute value.
    Python_abs()-An abs() function gives the actual or absolute value of the given number.If that may be complicated number abs() returns its magnitude.

    For example:
    number = -15
    absolute_number = abs(number)
    print(absolute_number)
    # Output: 15

    num-a number whose absolute value is to be returned.The number will be
    Integer
    floating number
    complex number

    User-defined functions:
    Functions which will be defined by ourselves to do specific tasks are referred to as user-defined functions.
    For example:
    def add(x + y)
    print(“addition”, “x + y”)
    return x + y

  5. A.The function in python programming is called a group of that is linked statements that do some specific task. Functions will help to decompose the program into smaller and modular chunks.
    When we have defined the function we can call it from another function, program, or maybe even a python prompt. To call a function name with proper parameters like

    >>>greet(‘Rakul’)

    HI Rakul.Good Evening!

    When we try executing the program with the function to see the output.

    ef greet(name):

    “””
    This function greets to the person passed in as a parameter “””

    print(“HI, ” + name + “. Good Evening!”)

    greet(‘Rakul’)
    B.Types of functions

    1. Built-in Functions-Functions that are created to python.

    Python_abs() will return value absolute number.

    Python_abs()-An abs() function gives the actual or absolute value of the given number.If that may be complicated number abs() returns its magnitude.For example

    number = -20

    absolute_number = abs(number)

    print(absolute_number)
    # Output: 20

    abs() syntax

    the abs() syntax method is

    abs(num)

    abs()parameters

    abs() method takes a single argument:

    num-a number whose absolute value is to be returned.The number will be 

     integer

    floating number

    complex number
    2. User-defined functions

    Functions to which we will be defining ourselves to do certain specific tasks are referred to as user-defined functions. The way in which we define and call function in python is already told.

    Advantages are

    user-defined functions are supports to break big program to small pieces of segments that makes program quiet simple to understand.
    It is repeated code has in a program function that can be used to include those codes and execute when needed by calling that function.

    Consider an example

    Program to illustrate

    # the use of user-defined functions
    def add_numbers(x,y):

       sum = x + y

       return sum

    num1 = 5

    num2 = 6

    print(“The sum is”, add_numbers(num1, num2))

    output

    Enter a number: 2.4
    Enter another number: 6.5

    The sum is 8.9

  6. The function in python programming is called a group of that is linked statements that do some specific task. Functions will help to decompose the program into smaller and modular chunks. As the program grows large and larger, the function is going to make more systematic and manageable. It always avoids repetition and makes the code reusable.

    Built-in Functions-Functions that are created to python.
    Python_abs() will return value absolute number.

    Python_abs()-An abs() function gives the actual or absolute value of the given number. If that may be complicated number abs() returns its magnitude. For example

    number = -20

    absolute_number = abs(number)

    print(absolute_number)

    # Output: 20

    abs() syntax

    the abs() syntax method is

  7. 1. What are Python functions and its declaration with an example?

    The function in python programming is called a group of that is linked statements that do some specific task. Functions will help to decompose the program into smaller and modular chunks. As the program grows large and larger, the function is going to make more systematic and manageable. It always avoids repetition and makes the code reusable.

    The syntax of function is
    def function_name(parameters):
    “””docstring”””
    statement
    2. Explain the types of functions in Python with an example?

    Built-in Functions and User-defined functions. Built-in functions are Functions that are created to python and User-defined functions are Functions to which we will be defining ourselves to do certain specific tasks are referred to as user-defined functions. The way in which we define and call function in python is already told.

    Example of built-in function is
    number = -20
    absolute_number = abs(number)
    print(absolute_number)
    # Output: 20
    abs() syntax
    the abs() syntax method is
    abs(num)
    abs()parameters
    abs() method takes a single argument:
    • num-a number whose absolute value is to be returned.The number will be
    integer
    floating number
    complex number

    An example of user-defined function is
    # the use of user-defined functions
    def add_numbers(x,y):
    sum = x + y
    return sum
    num1 = 5
    num2 = 6
    print(“The sum is”, add_numbers(num1, num2))
    output
    Enter a number: 2.4
    Enter another number: 6.5
    The sum is 8.9

  8. What are Python functions and its declaration with an example?
    A function is a block of organized, reusable code that is used to perform a single, related action.
    Functions provide better modularity for your application and a high degree of code reusing.
    As you already know, Python gives you many built-in functions like print, etc. but you can also
    create your own functions. These functions are called user-defined functions.
    Defining a Function You can define functions to provide the required functionality. Here are simple rules to define a
    function in Python.
    Function blocks begin with the keyword def followed by the function name and parentheses ().
    Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
    The first statement of a function can be an optional statement – the documentation string of
    the function or docstring.
    The code block within every function starts with a colon : and is indented.
    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.
    Examples:
    Python List Functions
    Commonly Used Python List Functions
    #1) len()
    #2) list()
    #3) range()
    #4) sum()
    #5) min()
    #6) max()
    #7) sorted()
    #8) reversed()
    #9) enumerate()
    #10) zip()
    #11) map()
    #12) filter()
    #13) iter()
    Other Python List Built-in Functions
    #14) all()
    #15) any()

  9. 1. Functions in python are a group of linked statements that will do some specific tasks. It will decompose the program into smaller and modular chunks. They avoid repetition and makes the code reusable.
    The syntax of function is
    def function_name(parameters):
    “””docstring”””
    Statement

    2. There are built in functions and user defined functions in python. Built in means that functions are created to python. Python_abs() gives the actual or absolute value of the given number
    number = -20
    absolute_number = abs(number)
    print(absolute_number)
    # Output: 20
    abs() syntax
    the abs() syntax method is
    abs(num)
    abs()parameters
    abs() method takes a single argument:
    • num-a number whose absolute value is to be returned.The number will be
    integer
    floating number
    complex number
    User defined functions are functions which we will define ourselves to do specific tasks. They break big programs to small segments and it has repeated code and can be executed when needed when called.
    Consider an example
    Program to illustrate
    # the use of user-defined functions
    def add_numbers(x,y):
    sum = x + y
    return sum
    num1 = 5
    num2 = 6
    print(“The sum is”, add_numbers(num1, num2))
    output
    Enter a number: 2.4
    Enter another number: 6.5
    The sum is 8.9

  10. 1) What are Python functions and its declaration with an example?
    A) The function in python programming is called a group of that is linked statements that do some specific task. Functions will help to decompose the program into smaller and modular chunks. As the program grows large and larger, the function is going to make more systematic and manageable. It always avoids repetition and makes the code reusable.
    The syntax of function is
    def function_name(parameters):
    “””docstring”””

    2) Explain the types of functions in Python with an example?
    A) In Python, there are several types of functions that can be defined based on their purpose and behavior. Here are some of the most common types of functions in Python:
    (a) Built-in functions: These are functions that are built into the Python language and are available for use without requiring any special imports or packages. Examples include “print()”, “len()”, and “range()”.
    (b) User-defined functions: These are functions that are defined by the user to perform a specific task. They can be called and used like any other built-in function in Python.
    Program to illustrate

    # the use of user-defined functions
    def add_numbers(x,y):
    sum = x + y
    return sum
    num1 = 5
    num2 = 6
    print(“The sum is”, add_numbers(num1, num2))
    output
    Enter a number: 2.4
    Enter another number: 6.5
    The sum is 8.9
    statement

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class