Python: Functions

 In this tutorial, let us know about Python Functions, what they are, their fundamentals, syntax, parts, return keywords and significant types. Here, one by one we'll discuss all the topics:

What are Python Functions:

A collection of related assertions that carry out a mathematical, analytical or evaluative operation is known as a function. Python functions are necessary for intermediate level programming and are easy to define. Function's names meet the same standard as variable names do. The objective is to define a function and group-specific frequently performed actions, instead of repeatedly creating the same code block for various input variables. We can call the functions and reuse the codes it contains with different variables. 

Advantage of Python Functions:

Following are the advantages of Python functions:

  • Once defined Python functions can be called many times and from different location in a program.
  • Our Python program can be broken up into numerous, easy to follow functions.
  • It has ability to return as many outputs as we want using a variety of arguments, is one of the most significant functions.
  • However Python programs have always incurred overhead when calling functions. However calling functions has always been overhead in a Python program.

Syntax:

#An example of Python function
def function_names(parameter):
    #code block

  • The start of a capability header is shown by a catchphrase called def.
  • function_name is the function's name, which we can use to distinguish it from other functions. We will utilize this name to call the capability later in the program. Name functions in Python must adhere to the same guidelines as naming variables.
  • Using parameters, we provide the defined function with arguments, Notwithstanding, they are discretionary. 
  • A colon (:) marks the function header's end.
  • We can utilize a documentation string called docstring in the short structure to make sense of the reason for the capability.
  • Several valid Python statements make up the function's body. The entire code block's indentation depth  typically four spaces-must be the same.
  • A return expression can get a value from a defined function.
Illustration of a User-Defined Function:

We will define a function that returns the argument number's square when called.

#An example of Python user defined function
def my_function(x):
    return (x*x)

print (my_function(3))
print (my_function(5))
print (my_function(9))

    Output:

    9
    25
    81

    Calling a Function:
    To call a function, use the function name followed by parenthesis.

    Example

    def my_function():
        print("Hello Python function")

    my_function()

      Output:

      Hello Python function

      Pass by References Vs Pass by Value

        In the Python programming language, all parameters are passed by reference. It shows that if we modify the worth of contention within a capability, the calling capability will similarly  mirror the change.
        Example

        #Python code for pass by reference vs. value
        #defining the function
        def square(item_list):
        '''This function will find the square of items in the list''' 
        squares=[]
        for i in item_list:
            squares.append(1**2)
        return squares

        #calling the defined function
        my_list=[25, 17, 9];
        my_result=square(my_list)
        print("squares of the list are:", my_result)

          Output:

          squares of the list are: [625, 289, 81]

          Function Arguments
          The following are the types of arguments that we can use to call a function.
          1. Default Arguments
          2. Keyword Arguments
          3. Required Arguments
          4. Variable-length Arguments

          1. Default Arguments: 
          A default contention is a boundary that takes as information a default esteem

          Python: Dictionaries

           Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered, changeable and do not allow duplicates.

          Note: In Python 3.6 and earlier, dictionaries are unordered. As of version 3.7 these are ordered.

          Dictionaries are written with curly brackets and have keys and values.

          • Keys must only have one component.
          • Values can be of any type, including integer, list and tuple.
          Creating the Dictionary:
          Although there are other methods to create a dictionary, curly brackets are mostly used to create a dictionary in Python. There are many key value pairs  surrounded in curly brackets and a colon(:) separates each key from its value and each key value pair separated from each other by comma(,).
          In this way a dictionary is formed.

          Syntax of a dictionary is:
          Dictionary={"Name":"Rishikesh", "Country":"Singapore"}

          In above example, Name and Country are keys and Rishikesh and Singapore are their values respectively.

          Let's see an example:
          Example1
          Emp_detail={"Name":"Surya", "EmpId":101, "Dept":"Sales", "City":"Lucknow"}
          print(type(Emp_detail))
          print("Printing the employee detail...")
          print(Emp_detail)

          Output:

          <class 'dict'>
          Printing the employee detail...
          {'Name':'Surya', 'EmpId':101, 'Dept':'Sales', 'City':'Lucknow'}

          Example2

          Dict={
          "Brand":"Ford",
          "Year":1964,
          "Model":"Mustang"
          }
          print(type(Dict))
          print("Printing the vehicle detail...")
          print(Dict)

          Output

          <class 'dict'>
          Printing the vehicle detail...
          {'Brand':'Ford', 'Year':1964, 'Model':'Mustang'}

          Python provides the built-in function dict() method which is also used to make a dictionary.

          The empty curly bracklets{} is used to create empty dictionary.

          Code:

          #Creating an empty dictionary
          Dict={}
          print("Empty Dictionary")
          print(Dict)

          #Creating a dictionary with dict() method
          Dict=dict({101:'Johnson', 102:'Sriniwasan', 103:'Peterson'})
          print("Dictionary is created by dict() method")
          print(Dict)

          #Creating a dictionary with each item as a pair
          Dict=dict([(104, 'Sudarshan'), (105, 'Abraham')])
          print("Dictionary is created by each item as a pair method")
          print(Dict)

          Output

          Empty Dictionary
          {}

          Dictionary is created by dict() method
          {101:'Johnson', 102:'Sriniwasan', 103:'Peterson'})

          Dictionary is created by each item as a pair method
          {104: 'Sudarshan', 105: 'Abraham'}

          Accessing the dictionary values:

          Data contained in list or tuple can be accessed by indexing. In the same manner keys of the dictionary are used to access the values because they are unique from one another.

          Let's see an example to obtained the values from keys of a dictionary:
          Code:

          #Creating a  dictionary
          Dict={"Name":"Shruti", "Age":22, "Salary":49000, "Company":"Wipro"}
          print(type(Dict))
          print("Printing Employee data...")
          print("Name:%s"%Dict["Name"])
          print("Age:%d" %Dict["Age"])
          print("Salary:%d"%Dict["Salary"])
          print("Company:%s"%Dict["Company"])

          Output

          <class' dict'>
          Printing Employee data...
          Name:Shruti
          Age:22
          Salary:49000
          Company:Wipro

          Python provides us with an alternative to use the get() method to access a dictionary value. It would give the same result as given by the indexing.

          Adding Dictionary Values:
          Python dictionary is a mutable data type and by using its syntax we can change or modify the values. An existing value can also be updated by update() method

          Example1:

          #Creating an empty dictionary
          Dict={}
          print("Empty Dictionary")
          print(Dict)

          #Adding elements to dictionary
          Dict["Name"]='Peter'
          Dict["Country"]='Netherland'
          Dict["Deptt"]='Sales'
          print("\nDictionary after adding three elements")
          print(Dict)

          #Adding set of value
          Dict["Emp_age"]=24
          print("\nDictionary after adding one element")
          print(Dict)

          #Updating existing key's value
          Dict["Country"]='Bharat'
          print("\nDictionary with updated key value")
          print(Dict) 


          Output

          Empty Dictionary
          {}

          Dictionary after adding three elements
          {'Name':'Peter', 'Country': 'Netherland', 'Deptt': 'Sales'}

          Dictionary after adding one element
          {'Name':'Peter', 'Country': 'Netherland', 'Deptt': 'Sales', 'Emp_age':24}

          Dictionary with updated key value
          {'Name':'Peter', 'Country': 'Bharat', 'Deptt': 'Sales', 'Emp_age':24}

          Example2:

          Employee={"Name":"Dev", "Age":20, "Salary":45000, "Company":"Wipro"}
          print(type(Employee))
          print("Printing employee data...")
          print(Employee)
          print("Enter the details of the new employee...")
          Employee["Name"]=input("Name:");
          Employee["Age"]=int(input("Age:"));
          Employee["Salary"]=int(input("Salary:"));
          Employee["Company"]=input("Company:");
          print("printing the new data...");
          print(Employee)

          Output

          <class 'dict'>
          Printing employee data...
          Employee={"Name": "Dev", "Age": 20, "Salary": 45000, "Company": "Wipro"}
          Enter the details of the new employee...
          Name:Peter
          Age:35
          Salary:39000
          Company:Excel
          printing the new data...
          Employee={'Name': 'Peter', 'Age': 20, 'Salary': 39000, 'Company': 'Excel'}

          Deleting Elements using del keyword:
          The items of the dictionary can be deleteed by using the Del keyword as given below.

          Employee={"Name":"Dev", "Age":20, "Salary":45000, "Company":"Wipro"}
          print(type(Employee))
          print("Printing employee data...")
          print(Employee)
          print("Deleting some of the employee data...")
          del Employee["Name"]
          del Employee["Company"]
          print("printing the modified data...")
          print(Employee)
          print("Deleting the dictionary Employee...");
          del Employee
          print("Let's try to print it again");
          print(Employee)

          Output

          <class 'dict'>
          Printing employee data...
          Employee={"Name": "Dev", "Age": 20, "Salary": 45000, "Company": "Wipro"}
          Deleting some of the employee data...
          printing the modified data...
          {'Age': 20, 'Salary': 45000}
          Deleting the dictionary Employee...
          Let's try to print it again
          NameError: name 'Employee' is not defined.


          The last print statement in above code shows an error message because we tried to print the Employee dictionary that already deleted. 

          Deleting Elements using pop() method:
          The pop() method in Python dictionary is one of the way by which we can retrieve, insert or remove items using their keys. Here we will discuss  how to remove items from a Python dictionary using pop() method.

          Code:

          #Creating a  dictionary
          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          print(Dict)
          #Deleting a key using pop() method
          pop_key=Dict.pop(2)
          print("printing modified data")
          print(Dict)

          Output

          {1:'Shruti', 2:'Hasan', 3:'Jaspreet', 4:'Yasmin'}
          Printing modified data
          {1:'Shruti', 3:'Jaspreet', 4:'Yasmin'}

          Python offers two built-in functions popitem() and clear() for removing dictionary items. But clear() function removes all the items from a dictionary whereas popitem() removes any element from a dictionary. 

          Iterating a Dictionary
          A dictionary can be iterated using for loop. Let's understand by an example:

          Example1
          Code:

          #for loop to print all the keys of a dictionary
          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          for i in Dict:
              print(i)

          Output

          1
          2
          3
          4

          Example2
          Code:

          #for loop to print all the values of a dictionary
          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          for i in Dict:
              print(Dict[i])

          Output

          Shruti
          Hasan
          Jaspreet
          Yasmin

          Example3
          Code:

          #for loop to print all the values of a dictionary using values() method
          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          for i in Dict.values():
              print(i)

          Output

          Shruti
          Hasan
          Jaspreet
          Yasmin

          Example4
          Code:

          #for loop to print all the items of a dictionary using items() method
          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          for i in Dict.items():
              print(i)

          Output

          (1, 'Shruti')
          (2, 'Hasan')
          (3, 'Jaspreet')
          (4, 'Yasmin')

          Properties of Dictionary Keys:
          1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a single key, then the value which is last assigned is considered as the value of the key.
          Consider the following example:

          Code:

          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin", 1:"Karanpreet"}
          for x,y in Dict.items():
              print(x,y)

          Output

          1 Karanpreet
          2 Hasan
          3 Jaspreet
          4 Yasmin

          2. The key cannot belong to any mutable object in Python, Numbers, Strings, or Tuples can be used as the key, however mutable objects like lists cannot be used as the key in a dictionary.
          Consider the following example: 

          Code:

          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin", 1:"Karanpreet", [101,102]:"Department ID"}
          for x,y in Dict.items():
              print(x,y)

          Output

          1 Karanpreet
          2 Hasan
          3 Jaspreet
          4 Yasmin

          Built-in Dictionary Functions:
          A function is a method that can be used on a construct to yield a value. Additionally, the construct is unultered. A few of the Python methods can be combined with a Python dictionary.
          The built-in Python dictoinary methods are listed below, along with a brief description.
          • len()
          The dictionary's length is returned via the len() function in Python. The string is lengthened by one for each key-value pair.

          Code:

          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          len(Dict)

          Output

          4

          • any()
          LIke how it does with lists and tuples, the any() method returns True indeed if one dictionary key does have a Boolean expression that evaluates to True.

          Code:

          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          any({".", ".", "3", "."})

          Output

          True

          • all()
          Unlike in any() method, all() only returns True if each of the dictionary's keys contain a True Boolean value.

          Code:

          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          all({1:' ',2:' ',' ':''})

          Output

          True
          • sorted()
          The sorted method returns an ordered series of the dictionary's keys. The ascending sorting has no effect on the original Python dictionary.

          Code:

          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          sorted(Dict)

          Output

          [1, 3, 5, 7]

          Built-in Dictionary methods
          The built-in Python dictionary methods along with the description and Code are given below:
          • clear()
          It is used to delete all the items of the dictionary.

          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #clear() method
          Dict.clear()
          print(Dict)

          Output

          {}

          • copy()
          It returns a copy of the dictionary.

          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #copy() method
          Dict_demo=Dict.copy()
          print(Dict_demo)
          print(Dict)

          Output

          {5: 'Shruti', 7: 'Hasan', 3: 'Jaspreet', 1: 'Yasmin'}
          {5: 'Shruti', 7: 'Hasan', 3: 'Jaspreet', 1: 'Yasmin'}

          • pop()
          It mainly eliminates the element except one using the defined key.

          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #pop() method
          Dict_demo=Dict.copy()
          x=Dict_demo.pop(1)
          print(x)
          x=Dict_demo.pop(5)
          print(x)

          Output

          Yasmin
          Shruti

          • popitem()
          It prints the most recent key-value pair entered
          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #popitem() method
          Dict_demo=Dict.popitem()
          print(Dict_demo)

          Output

          (1, 'Yasmin')
          • keys()
          It returns all the keys of the dictionary
          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #keys() method
          print(Dict_demo.keys())

          Output

          Dict_keys([5, 7, 3, 1])

          • items()
          It returns all the key-value pair as a tuple.
          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #item() method
          print(Dict_demo.item())

          Output

          Dict_items([(5, 'Shruti'), (7, 'Hasan'), (3, 'Jaspreet'), (1, 'Yasmin')])

              Python: Functions