Python 3x Pandas Django

Python Functions


Function is a block of code which only runs when it is called

Creating a function

def myfunction():
  print("this code shows python function definitions")

Calling a function

def myfunction():
  print("this code shows python function definitions")

 myfunction();  #Output: this code shows python function definitions

Parameters

You can pass data, known as parameters, into a function

A parameter is the variable listed inside the parentheses in the function definition

def myfunction( name, country ):
  print("My name is " + name + " from " + country)

myfunction("Michael", "US") #Output: My name is Michael from US

Default Parameters

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.

def myfunction(name, country ='US'):
  print("My name is " + name + " from " + country)

myfunction("Michael")

myfunction("Michael", "US")
myfunction("Michael", "India")

In the example, the country has default value "US" and no argument is passed during the function call myfunction("Michael") and you may notice that the print statement displays the default value "US".

Output:

My name is Michael from US
My name is Michael from US
My name is Michael from India

Arguments

An argument is the value that is sent to the function when it is called.

No. of arguments in the calling function should match with the parameters defined in the function definition.

def myfunction(name):
  print("My name is: " + name)

myfunction("Michael") #Output: My name is: Michael

This type of arguments are positional arguments.

Positional arguments are arguments that required to be in the proper position. if we define a function parameter name 1st and country 2nd and you have to make sure that the first argument will be the name & the second argument will be the country.

Example

def myfunction( name, country ):
  print("My name is " + name + " from " + country)

myfunction("Michael", "US") #Output: My name is Michael from US

Keyword Arguments

A keyword argument is where you provide a name to the variable as you pass it into the function

def myfunction( name, country ):
  print("My name is " + name + " from " + country)

myfunction(country = "US", name = "Michael") #Output: My name is Michael from US

This is not recommended way because you are making the code more complicated than its needs to be if this definition of the function is to give a name and country you should follow the practice in not configure other developers than just stick to that name and country.

return Keyword

return statement is a special statement that you can use inside a function or method to send the function's result back to the caller. The return value of a Python function can be any Python object(including None).

def mySum( a, b ):
  return a + b

result = mySum(10,23)
print(result)       #Output: 33

return None

def mySum( a, b ):
  print('Sum of a & b is ', str(a+b)) #Output: Sum of a & b is  33
  return None

result = mySum(10,23)
print(result) #Output                 #Output: None

*args and **kwargs in Python

If you do not know how many arguments that will be passed into your function, add * before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the items accordingly

def myfunction(*args):
  for items in args:
      print(items)

myfunction("jan", "feb", "mar") #Output: jan feb mar

myfunction("jan", "feb", "mar", "apr", "may") #Output: jan feb mar apr may

In the above example, you could see a calling myfunction with different numbers of value ("jan", "feb", "mar" & "jan", "feb", "mar", "apr", "may") on each time

There are two different types of passing arguments that can use this Special Symbols '*'

1. *args (Non-Keyword Arguments)

2. **kwargs (Keyword Arguments)

We use *args and **kwargs as an argument when we have no doubt about the number of arguments we should pass in a function

1. *args (Non-Keyword Arguments)

def myfunction(*args):
  for items in args:
      print(items)

var_jan = "jan"
myfunction(var_jan, "feb", "mar") #Output: jan feb mar

In the above example, function will receive a tuple of arguments, and can access the items accordingly

2. **kwargs (Keyword Arguments)

a. A keyword argument is where you provide a name to the variable as you pass it into the function

b. One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out

def myfunction(**kwargs):
    for key, value in kwargs.items():
        print ("%s == %s" %(key, value))

myfunction(jan ='January', feb ='february', mar='march')

#Output:
jan == January
feb == february
mar == march

IMPORTANT: You can define a function with params, *args, default parameters & **kwargs all together but you should follow this rule params, *args, default parameters & **kwargs.

def myFunc(name, *args, country='US', **kwargs):
    somethings..

First-Class Objects

Functions are first-class objects because it is can pass around and used as arguments, just like other objects in python (string, int, float, list, and so on).

Example

def say_hello(name):
    return f"Hello {name}"

def ask_question(name):
    return f"Hi {name}, How are you?"

def robot_talk(robot_func):
    return robot_func("Ram")

say_hello() and ask_question() are regular functions that expect a string objects as its arguments.

The robot_talk() function expects a function as its argument.

For instance, pass it the say_hello() or the ask_question() function:

print(robot_talk(say_hello))    #Output: Hello Ram
print(robot_talk(ask_question)) #Output: Hi Ram, How are you?

Note that robot_talk(say_hello), say_hello function is named without parentheses. This means that only a reference to the function is passed. The function say_hello is not executed. The robot_talk() function is written with parentheses, so it will be called as usual and displayed the output.

Inner Functions

It’s also possible to define functions inside other functions. Such functions are called inner functions.

The inner functions are not defined until the parent function is called.

They are locally scoped to parent() and they only exist inside the parent() function.

def parent():
    print("Printing from the parent() function")

    def first_child():
        print("Printing from the first_child() function")

    def second_child():
        print("Printing from the second_child() function")

    second_child()
    first_child()

#MainBlock
print(parent())

Output:

Printing from the parent() function
Printing from the second_child() function
Printing from the first_child() function

Returning Functions From Functions

Python also allows you to use functions as return values

def parent(name):
    def first_child():
        return "Hi, I am first child"

    def second_child():
        return "Hi, I am second child "

    if name == "first":
        return first_child
    else:
        return second_child

Output

print(parent("first"))      #<'function parent.<'locals>.first_child at 0x000001980DF63828>
print(parent("second"))     #<'function parent.<'locals>.second_child at 0x000001980DF63708>

first  = parent("first")
second = parent("second")

print(first())            #Output: Hi, I am first child
print(second())           #Output: Hi, I am second child

# Another way to execute these functions

print(parent("first")())  #Output: Hi, I am first child
print(parent("second")()) #Output: Hi, I am second child

parameters and return innner function

def mySum(num1, num2):
    def anotherFunction(n1, n2):
        return n1 + n2
    return anotherFunction(num1, num2)

result = mySum(10, 23)
print(result)

Output:

33

For more detial, please refer Python Build in Functions and Python String Methods

Docstrings

def mySum(num1, num2):
    ''' info: This function prints sum of two numbers '''
    return num1 + num2

result = mySum()
print(result)

Docstrings

Python docstrings are the string literals that appear right after the definition of a function, method, class, or module.

There are number of ways to see this docstrings.

1. Python IDE when the function block is called

2. __doc__ attribute

3. help()

Docstrings Definition:

def mySum(num1, num2):
    ''' info: This function prints sum of two numbers '''
    return num1 + num2

Output:

docstrings

Above screenshot from Spyder Anaconda3 IDE

Example __doc__ :

def mySum(num1, num2):
    ''' info: This function prints sum of two numbers '''
    return num1 + num2

print(mySum.__doc__)

Output:

info: This function prints sum of two numbers

Example help():

def mySum(num1, num2):
    ''' info: This function prints sum of two numbers '''
    return num1 + num2

print(help(mySum))

Output:

Help on function mySum in module __main__:

mySum(num1, num2)
    info: This function prints sum of two numbers

None

nonlocal Keyword

It is used to work with variables inside nested functions, where the variable should not belong to the inner function. Use the keyword nonlocal to declare that the variable is not local.

Without nonlocal keyword
def outer():
    x = 10
    def inner():
        x = 20
        print("inner x:", x)

    inner()
    print("outer x:", x)

outer()

Output:

inner x: 20
outer x: 10

With nonlocal keyword
def outer():
    x = 10
    def inner():
        nonlocal x
        x = 20
        print("inner x:", x)

    inner()
    print("outer x:", x)

outer()

Output:

inner x: 20
outer x: 20

In the above examples, you can see the only difference nonlocal x variable definition and this nonlocal variable should not belong to the inner function (it's not considered as a local variable of inner() instead consider a parent variable of inner()) so the variable outer() of x updated with 20 and it prints both inner and outer the same values.


If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!