Python Functions

Python Functions

1. What is a Function

In programming, a function is a reusable block of code that executes a certain functionality when it is called. Functions are away to achieve the modularity and reusability in code. Modular programming is the process of subdividing a computer program into separate sub programs. Reusability is using already developed code according to our requirement with out writing from scratch. 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. The syntax of function is as under:

Python Function Syntax

2. How to Define and Call a Function

A function in Python consists of the following components.

  • Keyword def that marks the start of the function header.
  • A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.
  • Parameters (arguments) through which we pass values to a function. They are optional.
  • A colon (:) to mark the end of the function header.
  • One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  • An optional return statement to return a value from the function.
# Let us declare / define a simple function add_numbers() two add two numbers
def add_numbers():
  no1=int(input("Enter a integer number"))
  no2=int(input("Enter another integer number"))

To call a function we write the function name and parameters in ()

3. Defining and Calling a Python Function with parameters

While defining a function in Python, you can pass argument(s) into the function by putting them inside the parenthesis. At the time of the call of function we need to pass values to these arguments and they are matched according to their position in the function call. First value is assigned to 1st parameter , 2nd value is assigned to the 2nd parameter and so on. We does not define any data type . At the time of call the variables accept the data type according to the values passed.

def add_numbers(no1 , no2):

Let us discuss some examples with different types of values :Now When we call it as
Here no1 is defined as integer type and 10 value is assigned to it, no2 is also defined as integer and 23 value is assigned to it. The result will also be in integer.
add_numbers(23.4 , 343.3)
Here no1 is defined as float type and value 23.4 is assigned to it , no2 is also defined as float and 343.3 value is assigned to it. The result will also be in float.
add_numbers(23.4 , 343)
Here no1 is defined as float type and value 23.4 is assigned to it, and no2 is defined as integer and 343 value is assigned to it. The result will be in float.

4. Passing Parameter Values using Parameter Name

There is another way to call function when we specify variable name and its value during the function calling. Here we specify which variable should get which value . e.g : add_numbers(no2=1292.3, no1=56) Here parameter named no1 will get value 56 and variable named no2 will get 1292.3 . In this method position of the variable does not matter and value is assigned to matching function parameter. Note : If the variable name is not correct Python will generate error. Consider the following function example:

def fullName (firstName,middleName, lastName):
  return f"{firstName} {middleName} {lastName}"

* We can call the function and pass values by specifying parameter name. The name of the parameter should be same as mentioned during definition.
print( fullName(firstName=”Zubair”, middleName=”Asim”, lastName=”Khan”) )
* As we assigned parameter’s values to the variable name so their position does not matter .
print( fullName(middleName=”Asim”,lastName=”Khan”,firstName=”Zubair”) )
* We can also pass values to some variables without specifying variable name and some using variable name, but all positional values must be defined at the start. For Example :
print ( fullName(“Zubair”,lastName=”Khan”,middleName=”Asim”) )

5. Specifying Default Values to Parameters

We can specify default values to all or some parameters of function. Parameter without default values must be present at the start of the function. This will enables us to pass values for these parameters and in case values are not provided default values will be used.

def add_nos(no1,no2,no3=0,no4=0):
   print( no1+no2+no3+no3)
add_nos(10) # will generate error

# This function definition will generate generate error non default argument follows # default argument ; so all default arguments must be at the end
def add_nos(no1=0,no2,no3,no4=0):
   print( no1+no2+no3+no3)

6. Dealing with Unknown Number of Arguments

In Python we can specify a arguments that can handle arbitrary number of parameters. To define such type of variable we an asterisk (*) is placed before the variable name that holds the values of all non keyword variable arguments. The values given will be stored in a tuple and this tuple remains empty if no arguments are specified during the function call for this variable. For Example : Consider a pizzaOrder Function:

def pizzaOrder(size, flavor , *toppings):
    print(f"Your pizza of size {size} inches with flavor {flavor} having toppings {toppings}")
# Now we can call this function as :
pizzaOrder(12,"Fajita", "Olives")
pizzaOrder(12,"Chicken Tikka", "Chezious","Chicken")
pizzaOrder(12,"Fajita", "Olives", "Meat cubes", "Extra Cheeze")
# First two parameters are assigned to size and flavor and all remaining will be assigned to toppings.

Consider another example of a function to sum minimum two and maximum any numbers of values. Consider the definition of the function sumNos given below.

def sumNos(no1, no2, *others ):
   for i in others:
   return sum
 # we can now call the function as :

7. Dealing with Unknown Number of Key/Value Arguments

In Python we can also specify a arguments that can handle arbitrary number of parameters with key/value pair. To define such type of variable we place double asterisk (**) before the variable name that holds the values of all key/value pair arguments. Here that variable will work as a dictionary.

def empInfo(name, age,**nationality):
    print("Name : ", name)
    print("Age : ", age)
    for key, value in nationality.items():
        print("%s == %s" % (key, value))

# To run the function
empInfo("Hassan",56, nationality1='Pakistani')
empInfo("Ali",36, nationality1='Pakistani', nationality2='US', nationality3='UK')

8. Passing Information Back from Function

In Python we use the return statement to exit from a function and go back to the location from where the function is called. We can also return the specified value or data item to the caller using return statement. We can also return more than one values from function and also more than 1 type of data using return statement. Consider the following examples..

def addNumbers(no1,no2):
     return ans
# We can call this function as 
print("The function returned value ", a)
# The output will be : The function returned value  30

# We can also return more than one values from function. The function will return the value in the form of tuple
def addNumbers(no1,no2):
  return no1,no2,ans

print("The function returned values ", res)
# The output will be : The function returned values  (10, 40, 50)

# We can also return different data types of values from functions. The function will return the value in the form of tuple
def addNumbers(no1,no2):
  return "The answer is ",ans

print("The function returned values ", res)
# The output will be :The function returned values  ('The answer is ', 70)

9. Using Function as Variable

Functions can be used as variables . This is done by using function call in our expression. Consider the following example :

def addNumbers(no1,no2):
return no1+no2
def subtractNumbers(no1,no2):
return no1-no2
result = addNumbers(50,15) + subtractNumbers(50,15)

In the above case first of all subtractNumbers(50,15) will be called, after it is evaluated then function addNumbers(50,15) will be called . Then result of both functions will be added and result will be stored in the result variable.

10) Functions Within a Function

Python allows us to a function inside another function providing the required signature of the function. Consider the following code :

def commisionCalc(salary):
    if salary >= 80 :
      return salary*80
    elif salary >= 50:
      return salary * 50
    elif salary >= 20:
      return salary*20
      return 0
def salaryCalc(basic):
  grossSalary = basic + commisionCalc(basic)
  print(f"Your Gross Salary  is = {grossSalary}")

# The output will be :
Your Gross Salary  is = 3570

In Python we can also define a function inside another function. This is known as an inner function or a nested function. In Python, this kind of function can access names in the enclosing function. Consider the following code:

def outer_func(who):
    def inner_func():
        print(f"Hello, {who}")

# The output will be:
Hello, World!
Courtesy : 

You may also like...

Popular Posts

Leave a Reply

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