Author: Saim Khalid

  •  Arbitrary or Variable-length Arguments

    Arbitrary Arguments (*args)

    You may want to define a function that is able to accept arbitrary or variable number of arguments. Moreover, the arbitrary number of arguments might be positional or keyword arguments.

    • An argument prefixed with a single asterisk * for arbitrary positional arguments.
    • An argument prefixed with two asterisks ** for arbitrary keyword arguments.

    Arbitrary Arguments Example

    Given below is an example of arbitrary or variable length positional arguments −

    # sum of numbersdefadd(*args):
       s=0for x in args:
    
      s=s+x
    return s result = add(10,20,30,40)print(result) result = add(1,2,3)print(result)

    The args variable prefixed with “*” stores all the values passed to it. Here, args becomes a tuple. We can run a loop over its items to add the numbers.

    It will produce the following output −

    100
    6
    

    Required Arguments With Arbitrary Arguments

    It is also possible to have a function with some required arguments before the sequence of variable number of values.

    Example

    The following example has avg() function. Assume that a student can take any number of tests. First test is mandatory. He can take as many tests as he likes to better his score. The function calculates the average of marks in first test and his maximum score in the rest of tests.

    The function has two arguments, first is the required argument and second to hold any number of values.

    #avg of first test and best of following testsdefavg(first,*rest):
       second=max(rest)return(first+second)/2
       
    result=avg(40,30,50,25)print(result)

    Following call to avg() function passes first value to the required argument first, and the remaining values to a tuple named rest. We then find the maximum and use it to calculate the average.

    It will produce the following output −

    45.0
    

    Arbitrary Keyword Arguments (**kwargs)

    If a variable in the argument list has two asterisks prefixed to it, the function can accept arbitrary number of keyword arguments. The variable becomes a dictionary of keyword:value pairs.

    Example

    The following code is an example of a function with arbitrary keyword arguments. The addr() function has an argument **kwargs which is able to accept any number of address elements like name, city, phno, pin, etc. Inside the function kwargs dictionary of kw:value pairs is traversed using items() method.

    defaddr(**kwargs):for k,v in kwargs.items():print("{}:{}".format(k,v))print("pass two keyword args")
    addr(Name="John", City="Mumbai")print("pass four keyword args")# pass four keyword args
    addr(Name="Raam", City="Mumbai", ph_no="9123134567", PIN="400001")

    It will produce the following output −

    pass two keyword args
    Name:John
    City:Mumbai
    pass four keyword args
    Name:Raam
    City:Mumbai
    ph_no:9123134567
    PIN:400001

    Multiple Arguments With Arbitrary Keyword Arguments

    If the function uses mixed types of arguments, the arbitrary keyword arguments should be after positional, keyword and arbitrary positional arguments in the argument list.

    Example

    Imagine a case where science and maths are mandatory subjects, in addition to which student may choose any number of elective subjects.

    The following code defines a percent() function where marks in science and marks are stored in required arguments, and the marks in variable number of elective subjects in **optional argument.

    defpercent(math, sci,**optional):print("maths:", math)print("sci:", sci)
       s=math+sci
       for k,v in optional.items():print("{}:{}".format(k,v))
    
      s=s+v
    return s/(len(optional)+2) result=percent(math=80, sci=75, Eng=70, Hist=65, Geo=72)print("percentage:", result)

    It will produce the following output −

    maths: 80
    sci: 75
    Eng:70
    Hist:65
    Geo:72
    percentage: 72.4
  • PositionalOnly Arguments

    Positional Only Arguments

    It is possible in Python to define a function in which one or more arguments can not accept their value with keywords. Such arguments are called positional-only arguments.

    To make an argument positional-only, use the forward slash (/) symbol. All the arguments before this symbol will be treated as positional-only.

    Python’s built-in input() function is an example of positional-only arguments. The syntax of input function is −

    input(prompt ="")

    Prompt is an explanatory string for the benefit of the user. However, you cannot use the prompt keyword inside the parentheses.

    Example

    In this example, we are using prompt keyword, which will lead to error.

    name =input(prompt="Enter your name ")

    On executing, this code will show the following error message −

       name = input (prompt="Enter your name ")
    
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    TypeError: input() takes no keyword arguments

    Positional-Only Arguments Examples

    Let’s understand positional-only arguments with the help of some examples −

    Example 1

    In this example, we make both the arguments of intr() function as positional-only by putting “/” at the end.

    defintr(amt, rate,/):
       val = amt * rate /100return val
       
    print(intr(316200,4))

    When you run the code, it will show the following result −

    12648.0
    

    Example 2

    If we try to use the arguments as keywords, Python raises errors as shown in the below example.

    defintr(amt, rate,/):
       val = amt * rate /100return val
       
    print(intr(amt=1000, rate=10))

    On running this code, it will show following error message −

       interest = intr(amt=1000, rate=10)
    
              ^^^^^^^^^^^^^^^^^^^^^^^
    TypeError: intr() got some positional-only arguments passed as keyword arguments: 'amt, rate'

    Example 3

    A function may be defined in such a way that it has some keyword-only and some positional-only arguments. Here, x is a required positional-only argument, y is a regular positional argument, and z is a keyword-only argument.

    defmyfunction(x,/, y,*, z):print(x, y, z)
       
    myfunction(10, y=20, z=30)
    myfunction(10,20, z=30)

    The above code will show the following output −

    10 20 30
    10 20 30 
  • Positional Arguments

    Positional Arguments

    The list of variables declared in the parentheses at the time of defining a function are the formal arguments. And, these arguments are also known as positional arguments. A function may be defined with any number of formal arguments.

    While calling a function −

    • All the arguments are required.
    • The number of actual arguments must be equal to the number of formal arguments.
    • They Pick up values in the order of definition.
    • The type of arguments must match.
    • Names of formal and actual arguments need not be same.

    Positional Arguments Examples

    Let’s discuss some examples of Positional arguments −

    Example 1

    The following example shows the use of positional argument.

    Open Compiler

    defadd(x,y):
       z = x+y
       print("x={} y={} x+y={}".format(x,y,z))
    a =10
    b =20
    add(a, b)

    It will produce the following output −

    x=10 y=20 x+y=30
    

    Here, the add() function has two formal arguments, both are numeric. When integers 10 and 20 passed to it. The variable “a” takes 10 and “b” takes 20, in the order of declaration. The add() function displays the addition.

    Example 2

    Python also raises error when the number of arguments don’t match. If you give only one argument and check the result you can see an error.

    defadd(x,y):
       z=x+y
       print(z)
    a=10;
    add(a)

    The error generated will be as shown below −

    TypeError: add() missing 1 required positional argument: 'y'
    

    Example 3

    Similarly, if you pass more than the number of formal arguments an error will be generated stating the same −

    defadd(x,y):
       z=x+y
       print("x={} y={} x+y={}".format(x,y,z))
    add(10,20,30)

    Following is the output −

    TypeError: add() takes 2 positional arguments but 3 were given
    

    Example 4

    Data type of corresponding actual and formal arguments must match. Change a to a string value and see the result.

    defadd(x,y):
       z=x+y
       print(z)
    a="Hello"
    b=20
    add(a,b)

    It will produce the following error −

    z=x+y
    
     ~^~
    TypeError: can only concatenate str (not "int") to str

    Difference between Positional and Keyword argument

    The below table explains the difference between positional and keyword argument −

    Positional ArgumentKeyword Argument
    Only the names of arguments are used to pass data to the given function.Keyword arguments are passed to a function in name=value form.
    Arguments are passed in the order defined in function declaration.While passing arguments, their order can be changed.
    Syntax: function(param1, param2,…)Syntax: function(param1 = value1,…)
  • KeywordOnly Arguments

    Keyword-Only Arguments

    You can use the variables in formal argument list as keywords to pass value. Use of keyword arguments is optional. But, you can force the function to accept arguments by keyword only. You should put an astreisk (*) before the keyword-only arguments list.

    Let us say we have a function with three arguments, out of which we want second and third arguments to be keyword-only. For that, put * after the first argument.

    Example of Keyword-Only Arguments

    The built-in print() function is an example of keyword-only arguments. You can give list of expressions to be printed in the parentheses. The printed values are separated by a white space by default. You can specify any other separation character instead using “sep” argument.

    print("Hello","World", sep="-")

    It will print −

    Hello-World
    

    Example: Using “sep” as non-keyword Argument

    The sep argument of the print() function is keyword-only. Try using it as non-keyword argument.

    print("Hello","World","-")

    You’ll get different output, not as desired −

    Hello World -
    

    Using Keyword-Only argument in User-Defined Method

    To make an argument keyword-only, put the astreisk (*) before it while creating the user-defined function.

    Those Python functions that are defined by us within a given class to perform certain actions are called as user-defined function. They are not predefined by Python.

    Example

    In the following user defined function “intr()” the “rate” argument is keyword-only. To call this function, the value for rate must be passed by keyword.]

    defintr(amt,*, rate):
       val = amt*rate/100return val
       
    interest = intr(1000, rate=10)print(interest)
    100.0
    

    However, if you try to use the default positional way of calling the above function, you will encounter an error.

    Example

    The code below shows it is not possible to use positional arguments when keyword-only arguments are required.

    defintr(amt,*, rate):
       val = amt * rate /100return val
       
    interest = intr(1000,10)print(interest)

    On executing, this code will show the following result −

    interest = intr(1000, 10)
    
               ^^^^^^^^^^^^^^
    TypeError: intr() takes 1 positional argument but 2 were given

  • Keyword Arguments

    Keyword Arguments

    Python allows to pass function arguments in the form of keywords which are also called named arguments. Variables in the function definition are used as keywords. When the function is called, you can explicitly mention the name and its value.

    Calling Function With Keyword Arguments

    The following example demonstrates keyword arguments in Python. In the second function call, we have used keyword arguments.

    # Function definition is heredefprintinfo( name, age ):"This prints a passed info into this function"print("Name: ", name)print("Age ", age)return# Now you can call printinfo function# by positional arguments
    printinfo ("Naveen",29)# by keyword arguments
    printinfo(name="miki", age =30)

    It will produce the following output −

    Name: Naveen
    Age 29
    Name: miki
    Age 30
    

    Order of Keyword Arguments

    By default, the function assigns the values to arguments in the order of appearance. However, while using keyword arguments, it is not necessary to follow the order of formal arguments in function definition. Use of keyword arguments is optional. You can use mixed calling. You can pass values to some arguments without keywords, and for others with keyword.

    Example

    Let us try to understand with the help of following function definition −

    defdivision(num, den):
       quotient = num/den
       print("num:{} den:{} quotient:{}".format(num, den, quotient))
    
    division(10,5)
    division(5,10)

    Since the values are assigned as per the position, the output is as follows −

    num:10 den:5 quotient:2.0
    num:5 den:10 quotient:0.5
    

    Example

    Instead of passing the values with positional arguments, let us call the function with keyword arguments −

    defdivision(num, den):
       quotient = num/den
       print("num:{} den:{} quotient:{}".format(num, den, quotient))
       
    division(num=10, den=5)
    division(den=5, num=10)

    Unlike positional arguments, the order of keyword arguments does not matter. Hence, it will produce the following output −

    num:10 den:5 quotient:2.0
    num:10 den:5 quotient:2.0
    

    However, the positional arguments must be before the keyword arguments while using mixed calling.

    Example

    Try to call the division() function with the keyword arguments as well as positional arguments.

    defdivision(num, den):
       quotient = num/den
       print("num:{} den:{} quotient:{}".format(num, den, quotient))
    
    division(num =5,10)

    As the Positional argument cannot appear after keyword arguments, Python raises the following error message −

        division(num=5, 10)
    
                      ^
    SyntaxError: non-keyword arg after keyword arg
  • Default Arguments

    Python Default Arguments

    Python allows to define a function with default value assigned to one or more formal arguments. Python uses the default value for such an argument if no value is passed to it. If any value is passed, the default value is overridden with the actual value passed.

    Default arguments in Python are the function arguments that will be used if no arguments are passed to the function call.

    Example of Default Arguments

    The following example shows use of Python default arguments. Here, the second call to the function will not pass value to “city” argument, hence its default value “Hyderabad” will be used.

    # Function definition defshowinfo( name, city ="Hyderabad"):"This prints a passed info into this function"print("Name:", name)print("City:", city)return# Now call showinfo function
    showinfo(name ="Ansh", city ="Delhi")
    showinfo(name ="Shrey")

    It will produce the following output −

    Name: Ansh
    City: Delhi
    Name: Shrey
    City: Hyderabad
    

    Example: Calling Function Without Keyword Arguments

    Let us look at another example that assigns default value to a function argument. The function percent() has a default argument named “maxmarks” which is set to 200. Hence, we can omit the value of third argument while calling the function.

    # function definition defpercent(phy, maths, maxmarks=200):
       val =(phy + maths)*100/maxmarks
       return val
    
    phy =60
    maths =70# function calling with default argument
    result = percent(phy, maths)print("percentage:", result)
    
    phy =40
    maths =46
    result = percent(phy, maths,100)print("percentage:", result)

    On executing, this code will produce the following output −

    percentage: 65.0
    percentage: 86.0
    

    Mutable Objects as Default Argument

    Python evaluates default arguments once when the function is defined, not each time the function is called. Therefore, If you use a mutable default argument and modify it within the given function, the same values are referenced in the subsequent function calls.

    Those Python objects that can be changed after creation are called as mutable objects.

    Example

    The code below explains how to use mutable objects as default argument in Python.

    deffcn(nums, numericlist =[]):
       numericlist.append(nums +1)print(numericlist)# function calls
    fcn(66)
    fcn(68)
    fcn(70)

    On executing the above code, it will produce the following output −

    [67]
    [67, 69]
    [67, 69, 71]
  • Functions

    A Python 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.

    A top-to-down approach towards building the processing logic involves defining blocks of independent reusable functions. A Python function may be invoked from any other function by passing required data (called parameters or arguments). The called function returns its result back to the calling environment.

    python functions

    Types of Python Functions

    Python provides the following types of functions −

    Sr.NoType & Description
    1Built-in functionsPython’s standard library includes number of built-in functions. Some of Python’s built-in functions are print(), int(), len(), sum(), etc. These functions are always available, as they are loaded into computer’s memory as soon as you start Python interpreter.
    2Functions defined in built-in modulesThe standard library also bundles a number of modules. Each module defines a group of functions. These functions are not readily available. You need to import them into the memory from their respective modules.
    3User-defined functionsIn addition to the built-in functions and functions in the built-in modules, you can also create your own functions. These functions are called user-defined functions.

    Defining a Python Function

    You can define custom 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.

    Syntax to Define a Python Function

    deffunction_name( parameters ):"function_docstring"
       function_suite
       return[expression]

    By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

    Once the function is defined, you can execute it by calling it from another function or directly from the Python prompt.

    Example to Define a Python Function

    The following example shows how to define a function greetings(). The bracket is empty so there aren’t any parameters. Here, the first line is a docstring and the function block ends with return statement.

    defgreetings():"This is docstring of greetings function"print("Hello World")return

    When this function is called, Hello world message will be printed.

    Calling a Python Function

    Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the basic structure of a function is finalized, you can call it by using the function name itself. If the function requires any parameters, they should be passed within parentheses. If the function doesn’t require any parameters, the parentheses should be left empty.

    Example to Call a Python Function

    Following is the example to call printme() function −

    # Function definition is heredefprintme(str):"This prints a passed string into this function"print(str)return;# Now you can call the function
    printme("I'm first call to user defined function!")
    printme("Again second call to the same function")

    When the above code is executed, it produces the following output −

    I'm first call to user defined function!
    Again second call to the same function
    

    Pass by Reference vs Value

    In programming languages like C and C++, there are two main ways to pass variables to a function, which are Call by Value and Call by Reference (also known as pass by reference and pass by value). However, the way we pass variables to functions in Python differs from others.

    • call by value − When a variable is passed to a function while calling, the value of actual arguments is copied to the variables representing the formal arguments. Thus, any changes in formal arguments does not get reflected in the actual argument. This way of passing variable is known as call by value.
    • call by reference − In this way of passing variable, a reference to the object in memory is passed. Both the formal arguments and the actual arguments (variables in the calling code) refer to the same object. Hence, any changes in formal arguments does get reflected in the actual argument.
    Pass By Reference Vs Value

    Python uses pass by reference mechanism. As variable in Python is a label or reference to the object in the memory, both the variables used as actual argument as well as formal arguments really refer to the same object in the memory. We can verify this fact by checking the id() of the passed variable before and after passing.

    Example

    In the following example, we are checking the id() of a variable.

    deftestfunction(arg):print("ID inside the function:",id(arg))
    
    var ="Hello"print("ID before passing:",id(var))
    testfunction(var)

    If the above code is executed, the id() before passing and inside the function will be displayed.

    ID before passing: 1996838294128
    ID inside the function: 1996838294128
    

    The behavior also depends on whether the passed object is mutable or immutable. Python numeric object is immutable. When a numeric object is passed, and then the function changes the value of the formal argument, it actually creates a new object in the memory, leaving the original variable unchanged.

    Example

    The following example shows how an immutable object behaves when it is passed to a function.

    deftestfunction(arg):print("ID inside the function:",id(arg))
       arg = arg +1print("new object after increment", arg,id(arg))
    
    var=10print("ID before passing:",id(var))
    testfunction(var)print("value after function call", var)

    It will produce the following output −

    ID before passing: 140719550297160
    ID inside the function: 140719550297160
    new object after increment 11 140719550297192
    value after function call 10
    

    Let us now pass a mutable object (such as a list or dictionary) to a function. It is also passed by reference, as the id() of list before and after passing is same. However, if we modify the list inside the function, its global representation also reflects the change.

    Example

    Here we pass a list, append a new item, and see the contents of original list object, which we will find has changed.

    deftestfunction(arg):print("Inside function:",arg)print("ID inside the function:",id(arg))
       arg=arg.append(100)
       
    var=[10,20,30,40]print("ID before passing:",id(var))
    testfunction(var)print("list after function call", var)

    It will produce the following output −

    ID before passing: 2716006372544
    Inside function: [10, 20, 30, 40]
    ID inside the function: 2716006372544
    list after function call [10, 20, 30, 40, 100]
    

    Python Function Arguments

    Function arguments are the values or variables passed into a function when it is called. The behavior of a function often depends on the arguments passed to it.

    While defining a function, you specify a list of variables (known as formal parameters) within the parentheses. These parameters act as placeholders for the data that will be passed to the function when it is called. When the function is called, value to each of the formal arguments must be provided. Those are called actual arguments.

    function arguments

    Example

    Let’s modify greetings function and have name an argument. A string passed to the function as actual argument becomes name variable inside the function.

    defgreetings(name):"This is docstring of greetings function"print("Hello {}".format(name))return
       
    greetings("Samay")
    greetings("Pratima")
    greetings("Steven")

    This code will produce the following output −

    Hello Samay
    Hello Pratima
    Hello Steven
    

    Types of Python Function Arguments

    Based on how the arguments are declared while defining a Python function, they are classified into the following categories −

    • Positional or Required Arguments
    • Keyword Arguments
    • Default Arguments
    • Positional-only Arguments
    • Keyword-only arguments
    • Arbitrary or Variable-length Arguments

    Positional or Required Arguments

    Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition, otherwise the code gives a syntax error.

    Example

    In the code below, we call the function printme() without any parameters which will give error.

    # Function definition is heredefprintme(str):"This prints a passed string into this function"print(str)return;# Now you can call printme function
    printme()

    When the above code is executed, it produces the following result −

    Traceback (most recent call last):
       File "test.py", line 11, in <module>
    
      printme();
    TypeError: printme() takes exactly 1 argument (0 given)

    Keyword Arguments

    Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

    Example 1

    The following example shows how to use keyword arguments in Python.

    # Function definition is heredefprintme(str):"This prints a passed string into this function"print(str)return;# Now you can call printme function
    printme(str="My string")

    When the above code is executed, it produces the following result −

    My string
    

    Example 2

    The following example gives more clear picture. Note that the order of parameters does not matter.

    # Function definition is heredefprintinfo( name, age ):"This prints a passed info into this function"print("Name: ", name)print("Age ", age)return;# Now you can call printinfo function
    printinfo( age=50, name="miki")

    When the above code is executed, it produces the following result −

    Name:  miki
    Age  50
    

    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.

    Example

    The following example gives an idea on default arguments, it prints default age if it is not passed −

    # Function definition is heredefprintinfo( name, age =35):"This prints a passed info into this function"print("Name: ", name)print("Age ", age)return;# Now you can call printinfo function
    printinfo( age=50, name="miki")
    printinfo( name="miki")

    When the above code is executed, it produces the following result −

    Name:  miki
    Age  50
    Name:  miki
    Age  35
    

    Positional-only arguments

    Those arguments that can only be specified by their position in the function call is called as Positional-only arguments. They are defined by placing a “/” in the function’s parameter list after all positional-only parameters. This feature was introduced with the release of Python 3.8.

    The benefit of using this type of argument is that it ensures the functions are called with the correct arguments in the correct order. The positional-only arguments should be passed to a function as positional arguments, not keyword arguments.

    Example

    In the following example, we have defined two positional-only arguments namely “x” and “y”. This method should be called with positional arguments in the order in which the arguments are declared, otherwise, we will get an error.

    defposFun(x, y,/, z):print(x + y + z)print("Evaluating positional-only arguments: ")
    posFun(33,22, z=11)

    It will produce the following output −

    Evaluating positional-only arguments: 
    66
    

    Keyword-only arguments

    Those arguments that must be specified by their name while calling the function is known as Keyword-only arguments. They are defined by placing an asterisk (“*”) in the function’s parameter list before any keyword-only parameters. This type of argument can only be passed to a function as a keyword argument, not a positional argument.

    Example

    In the code below, we have defined a function with three keyword-only arguments. To call this method, we need to pass keyword arguments, otherwise, we will encounter an error.

    defposFun(*, num1, num2, num3):print(num1 * num2 * num3)print("Evaluating keyword-only arguments: ")
    posFun(num1=6, num2=8, num3=5)

    It will produce the following output −

    Evaluating keyword-only arguments: 
    240
    

    Arbitrary or 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 for a function with non-keyword variable arguments is this −

    deffunctionname([formal_args,]*var_args_tuple ):"function_docstring"
       function_suite
       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.

    Example

    Following is a simple example of Python variable-length arguments.

    # Function definition is heredefprintinfo( arg1,*vartuple ):"This prints a variable passed arguments"print("Output is: ")print(arg1)for var in vartuple:print(var)return;# Now you can call printinfo function
    printinfo(10)
    printinfo(70,60,50)

    When the above code is executed, it produces the following result −

    Output is:
    10
    Output is:
    70
    60
    50
    

    In the next few chapters, we will discuss these function arguments at length.

    Order of Python Function Arguments

    A function can have arguments of any of the types defined above. However, the arguments must be declared in the following order −

    • The argument list begins with the positional-only args, followed by the slash (/) symbol.
    • It is followed by regular positional args that may or may not be called as keyword arguments.
    • Then there may be one or more args with default values.
    • Next, arbitrary positional arguments represented by a variable prefixed with single asterisk, that is treated as tuple. It is the next.
    • If the function has any keyword-only arguments, put an asterisk before their names start. Some of the keyword-only arguments may have a default value.
    • Last in the bracket is argument with two asterisks ** to accept arbitrary number of keyword arguments.

    The following diagram shows the order of formal arguments −

    Order Of Formal Arguments

    Python Function with Return Value

    The return keyword as the last statement in function definition indicates end of function block, and the program flow goes back to the calling function. Although reduced indent after the last statement in the block also implies return but using explicit return is a good practice.

    Along with the flow control, the function can also return value of an expression to the calling function. The value of returned expression can be stored in a variable for further processing.

    Example

    Let us define the add() function. It adds the two values passed to it and returns the addition. The returned value is stored in a variable called result.

    Open Compiler

    defadd(x,y):
       z=x+y
       return z
    a=10
    b=20
    result = add(a,b)print("a = {} b = {} a+b = {}".format(a, b, result))

    It will produce the following output −

    a = 10 b = 20 a+b = 30
    

    The Anonymous Functions

    The functions are called anonymous when they are not declared in the standard manner by using the def keyword. Instead, they are defined using the lambda keyword.

    • 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.
    • Although it appears that lambda’s are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.

    Syntax

    The syntax of lambda functions contains only a single statement, which is as follows −

    lambda[arg1 [,arg2,.....argn]]:expression
    

    Example

    Following is the example to show how lambda form of function works −

    # Function definition is heresum=lambda arg1, arg2: arg1 + arg2;# Now you can call sum as a functionprint("Value of total : ",sum(10,20))print("Value of total : ",sum(20,20))

    When the above code is executed, it produces the following result −

    Value of total :  30
    Value of total :  40
    

    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 −

    • Global variables
    • Local variables

    Global vs. Local 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. When you call a function, the variables declared inside it are brought into scope.

    Example

    Following is a simple example of local and global scope −

    total =0;# This is global variable.# Function definition is heredefsum( arg1, arg2 ):# Add both the parameters and return them."
       total = arg1 + arg2;# Here total is local variable.print("Inside the function local total : ", total)return total;# Now you can call sum functionsum(10,20);print("Outside the function global total : ", total)

    When the above code is executed, it produces the following result −

    Inside the function local total :  30
    Outside the function global total :  0
  •  Nested Loops


    In Python, when you write one or more loops within a loop statement that is known as a nested loop. The main loop is considered as outer loop and loop(s) inside the outer loop are known as inner loops.

    The Python programming language allows the use of one loop inside another loop. A loop is a code block that executes specific instructions repeatedly. There are two types of loops, namely for and while, using which we can create nested loops.

    You can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa.

    Python Nested for Loop

    The for loop with one or more inner for loops is called nested for loop. A for loop is used to loop over the items of any sequence, such as a list, tuple or a string and performs the same action on each item of the sequence.

    Python Nested for Loop Syntax

    The syntax for a Python nested for loop statement in Python programming language is as follows −

    for iterating_var in sequence:for iterating_var in sequence:
    
      statements(s)
    statements(s)

    Python Nested for Loop Example

    The following program uses a nested for loop to iterate over months and days lists.

    months =["jan","feb","mar"]
    days =["sun","mon","tue"]for x in months:for y in days:print(x, y)print("Good bye!")

    When the above code is executed, it produces following result −

    jan sun
    jan mon
    jan tue
    feb sun
    feb mon
    feb tue
    mar sun
    mar mon
    mar tue
    Good bye!
    Python Nested while Loop
    The while loop having one or more inner while loops are nested while loop. A while loop is used to repeat a block of code for an unknown number of times until the specified boolean expression becomes TRUE.

    Python Nested while Loop Syntax
    The syntax for a nested while loop statement in Python programming language is as follows −

    while expression:
    while expression:
    statement(s)
    statement(s)
    Python Nested while Loop Example
    The following program uses a nested while loop to find the prime numbers from 2 to 100 −


    i = 2
    while(i < 25):
    j = 2
    while(j <= (i/j)):
    if not(i%j): break
    j = j + 1
    if (j > i/j) : print (i, " is prime")
    i = i + 1

    print ("Good bye!")
    On executing, the above code produces following result −

    2 is prime
    3 is prime
    5 is prime
    7 is prime
    11 is prime
    13 is prime
    17 is prime
    19 is prime
    23 is prime
    Good bye!
  •  pass Statement

    Python pass Statement

    Python pass statement is used when a statement is required syntactically but you do not want any command or code to execute. It is a null which means nothing happens when it executes. This is also useful in places where piece of code will be added later, but a placeholder is required to ensure the program runs without errors.

    For instance, in a function or class definition where the implementation is yet to be written, pass statement can be used to avoid the SyntaxError. Additionally, it can also serve as a placeholder in control flow statements like for and while loops.

    Syntax of pass Statement

    Following is the syntax of Python pass statement −

    pass

    Example of pass Statement

    The following code shows how you can use the pass statement in Python −

    for letter in'Python':if letter =='h':passprint('This is pass block')print('Current Letter :', letter)print("Good bye!")

    When the above code is executed, it produces the following output −

    Current Letter : P
    Current Letter : y
    Current Letter : t
    This is pass block
    Current Letter : h
    Current Letter : o
    Current Letter : n
    Good bye!
    Dumpy Infinite Loop with pass Statement
    This is simple enough to create an infinite loop using pass statement in Python.

    Example
    If you want to code an infinite loop that does nothing each time through, do it as shown below −

    while True: pass
    # Type Ctrl-C to stop
    Because the body of the loop is just an empty statement, Python gets stuck in this loop.

    Using Ellipses (...) as pass Statement Alternative
    Python 3.X allows ellipses (coded as three consecutive dots ...) to be used in place of pass statement. Both serve as placeholders for code that are going to be written later.

    Example
    For example if we create a function which does not do anything especially for code to be filled in later, then we can make use of ...

    def func1():
    # Alternative to pass
    ...

    # Works on same line too
    def func2(): ...
    # Does nothing if called
    func1()
    func2()
  • Continue Statement


    Python continue Statement

    Python continue statement is used to skip the execution of the program block and returns the control to the beginning of the current loop to start the next iteration. When encountered, the loop starts next iteration without executing the remaining statements in the current iteration.

    The continue statement is just the opposite to that of break. It skips the remaining statements in the current loop and starts the next iteration.

    Syntax of continue Statement

    looping statement:
       condition check:continue

    Flow Diagram of continue Statement

    The flow diagram of the continue statement looks like this −

    loop-continue

    Python continue Statement with for Loop

    In Python, the continue statement is allowed to be used with a for loop. Inside the for loop, you should include an if statement to check for a specific condition. If the condition becomes TRUE, the continue statement will skip the current iteration and proceed with the next iteration of the loop.

    Example

    Let’s see an example to understand how the continue statement works in for loop.

    for letter in'Python':if letter =='h':continueprint('Current Letter :', letter)print("Good bye!")

    When the above code is executed, it produces the following output −

    Current Letter : P
    Current Letter : y
    Current Letter : t
    Current Letter : o
    Current Letter : n
    Good bye!
    

    Python continue Statement with while Loop

    Python continue statement is used with ‘for’ loops as well as ‘while’ loops to skip the execution of the current iteration and transfer the program’s control to the next iteration.

    Example: Checking Prime Factors

    Following code uses continue to find the prime factors of a given number. To find prime factors, we need to successively divide the given number starting with 2, increment the divisor and continue the same process till the input reduces to 1.

    num =60print("Prime factors for: ", num)
    d=2while num >1:if num%d==0:print(d)
    
      num=num/d
      continue
    d=d+1

    On executing, this code will produce the following output −

    Prime factors for: 60
    2
    2
    3
    5
    

    Assign different value (say 75) to num in the above program and test the result for its prime factors.

    Prime factors for: 75
    3
    5
    5