Python Devlopment






User-Defined Function



You use functions in programming to bundle a set of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub-program and called when needed. That means that a function is a piece of code written to carry out a specified task. To carry out that specific task, the function might or might not need multiple inputs. When the task is carried out, the function can or can not return one or more values.

There are three types of functions in Python:

  • Built-in functions, such as help() to ask for help, min() to get the minimum value, print()to print an object to the terminal.
  • User-Defined Functions (UDFs), which are functions that users create to help them out; And
  • Anonymous functions, which are also called lambda functions because they are not declared with the standard def keyword.

Functions vs Methods:

A method refers to a function which is part of a class. You access it with an instance or object of the class. A function doesn’t have this restriction: it just refers to a standalone function. This means that all methods are functions, but not all functions are methods.

Parameters vs Arguments:

Parameters are the names used when defining a function or a method, and into which arguments will be mapped. In other words, arguments are the things which are supplied to any function or method call, while the function or method code refers to the arguments by their parameter names.

1. Syntax of Basics Functions:

A function is a self-contained block of one or more statemenrs that performs a special task when called. The syntax for function is given as follows

def name_of_function(parameters):     # Function Header
    statement1         #Body of Function
    statement2
    statement3
    ......................
    ......................
    statementN

- Syntax of python function contains header and body

- Function header begins with keyword 'def'

- 'def' keyword signifies the begining of the function definition

- function header contains zero or more parameters

- These parameters are called formal parameters

- If function contains more than one parameters then all the parameters are seperated by commas.

- The function body is a block of statements.

#Write a program to create a function having function name 'display'. print the message, "Welcome to Government college of Engineering, Jalgaon" inside the function.

def display():
    print("Welcome to Government college of Engineering, Jalgaon")

display()              #Function call

#output
Welcome to Government college of Engineering, Jalgaon

In  the above program, a function having function name display() is created. This function takes no parameters. The body of a function contains only one statement. Finally, function display() is called to print message "Wlcome to Government College of Engineering, Jalgaon" within the block of the function.

2. Parameters and Arguments:

Parameters are used to give inputs to a function. They are specified with a pair of parenthesis in the function definition. When a programmers calls a function, the values are also passed to the function.

While parameters are defined by names tat appears in the functions defnition, arguments are values actually passed to a function when calling it. Thus, parameters define what types of arguments a function can accept.

Let us consider the examples of passing parameters to a function given as follows and use it to differentiate between arguments and parameters.

def printMax(num1,num2):
    statement1
    statement2
    ......................
    ......................
    statementN

printMax(10,20)                            # call a function(Invokes)

In the above example, printMax(num1,num2) has two parameters, viz. num1 and num2. The parameters num1 and num2 are also called formal parameters. A function is invoked by calling the name of function, i.e.printMax(10,20), where 10 and 20 are the actual parameters. Actual parameters are also called arguments. num1 and num2 are the parameters of a function.

Following example demonstrate the use of parameters and arguments in a function

#Python program to find maximum of two numbers.
def printMax(num1,num2):
    print("num1 = ",num1)
    print("num2 = ",num2)
    if(num1>num2):
        print("The numebr ",num1, "is greater than ",num2)
    elif(num2>num1):
        print("The numebr ",num2, "is greater than ",num1)
    else:
        print("Both Numbers ",num1,"and",num2,"are equal")

printMax(10,20)

#Output
num1 =  10
num2 =  20
The numebr  20 is greater than  10

3. The return Statement:

The return statement is used to return a value from the function. It is also used to return from a function, i.e. break out of the function.

# Write a python program to return the minimum of two numbers
def minimum(a,b):
    if(a<b):
        return(a)
    elif(b<a):
        return(b)
    else:
        return("Both the numbers are equal")

c=minimum(10,20)
print("Minimum Number is ",c)

#Output
Minimum Number is  10

3.1 Returning Multiple Values:

It is possible to return multiple values in python but it is not possible in c or c++

#Write a function add(num1,num2) to calculate and return at once the result of arithmetic operations such as addition and subtraction.
def add(num1,num2):
    a=num1+num2
    b=num1-num2
    return(a,b)

c=add(10,20)
print(c)

#Output
(30, -10)

3.2 Assign Returned Multiple Values to a Variable(s):

It is possible for a function to perform certain operations, return multiple values and assign the returned multiple values to a multiple variables.

#Write a program to return multiple values from a function and assign returned multiple values to a variables.
def compute(num1):
    print("Entered Number = ",num1)
    a=num1*num1
    b=num1*num1*num1
    return(a,b)

square,cube=compute(4)
print("Square = ",square)
print("Cube = ",cube)

#Output
Entered Number =  4
Square =  16
Cube =  64

4. How To Call A Function:

In the previous sections, you have seen a hello example already of how you can call a function. Calling a function means that you execute the function that you have defined - either directly from the Python prompt or through another function.

In above two examples, calling statements are

hello()

hello_noreturn()

5. Function Arguments in Python:

Earlier, you learned about the difference between parameters and arguments. In short, arguments are the things which are given to any function or method call, while the function or method code refers to the arguments by their parameter names. There are four types of arguments that Python UDFs can take:

  • No arguments
  • Default arguments
  • Required arguments
  • Keyword arguments

a. No Arguments:

IN this, if we defined function with no rguments then, not necessary to pass any argument as a parameter in function definitoon.

def hello():
  print("Hello World") 
  return 

b. Default Arguments:

Default arguments are those that take a default value if no argument value is passed during the function call. You can assign this default value by with the assignment operator =, just like in the following example:

# Define `add()` function
def add(a,b = 2):
  return a + b
  
# Call `add()` with only `a` parameter
c=add(a=1)
print("Addition is : ",c)

# Call `add()` with `a` and `b` parameters
c=add(a=1, b=3)
print("Addition is : ",c)

c. Required Arguments:

These arguments need to be passed during the function call and in precisely the right order, just like in the following example:

# Define `add()` with required arguments
def add(a,b):
  return a + b

c=add(10,20)
print("Addition is :",c)

d. Keyword Arguments:

If you want to make sure that you call all the parameters in the right order, you can use the keyword arguments in your function call. You use these to identify the arguments by their parameter name. Let’s take the example from above to make this a bit more clear:

# Define `add()` function
def add(a,b):
  return a + b
  
# Call `add()` function with parameters 
c=add(2,3)
print("Addtiton is : ",c)

# Call `add()` function with keyword arguments
c=add(a=1, b=2)
print("Addition is : ",c)

Note that by using the keyword arguments, you can also switch around the order of the parameters and still get the same result when you execute your function:

# Define `add()` function
def add(a,b):
  return a + b
  
# Call `add()` function with keyword arguments
c=add(b=2, a=1)
print("Addition is : ",c)

6. Anonymous OR Lambda Functions in Python:

Anonymous functions are also called lambda functions in Python because instead of declaring them with the standard def keyword, you use the lambda keyword.

Basic syntax of lambda function is

Name=lambda(variables):Code

Let us consider simple examples

double = lambda x: x*2

double(5)

In the DataCamp Light chunk above, lambda x: x*2 is the anonymous or lambda function. x is the argument, and x*2 is the expression or instruction that gets evaluated and returned. What’s special about this function is that it has no name, like the examples that you have seen in the first part of this functions tutorial. If you had to write the above function in a UDF, the result would be the following:

def double(x):
  return x*2

Let’s consider another example of a lambda function where you work with two arguments:

# `sum()` lambda function
sum = lambda x, y: x + y;

# Call the `sum()` anonymous function
sum(4,5)

# "Translate" to a UDF
def sum(x, y):
  return x+y

You use anonymous functions when you require a nameless function for a short period of time, and that is created at runtime.

7. Using main() as a Function:

If you have any experience with other programming languages such as Java, you’ll know that the main function is required to execute functions. As you have seen in the examples above, this is not necessarily needed for Python. However, including a main() function in your Python program can be handy to structure your code logically - all of the most important components are contained within this main() function.

You can easily define a main() function and call it just like you have done with all of the other functions above:

# Define `main()` function
def main():
  hello()
  print("This is a main function")

main()

However, as it stands now, the code of your main() function will be called when you import it as a module. To make sure that this doesn’t happen, you call the main() function when __name__ == '__main__'.

That means that the code of the above code chunk becomes:

# Define `main()` function
def main():
  hello()
  print("This is a main function")
  
# Execute `main()` function 
if __name__ == '__main__':
    main()

Lab Assignment:

Write a python script for the calculation of area of square, factorial of a given number, swapping of two numbers, finding leap year or not and calculation of HCF

def area_square():   #Function without parameter
    side=int(input("Enter side of a square : "))
    area=side*side
    print(area)

def factorial(n):    #Function with parameter
    fact=1
    for i in range(1,n+1):
        fact=fact*i
    print("Factorial of",n,"is",fact)

def swap(a,b):    #Function with multiple return
    temp=a
    a=b
    b=temp
    return(a,b)   #Multiple return type

def leapYear(year):
    if(year%4==0):
        if(year%100==0):
            if(year%400==0):
                print(year," is a Leap Year")
            else:
                print(year, "is not a Leap Year")
        else:
            print(year," is not a Leap Year")
    else:
        print(year," is not a Leap Year")
            
def HCF(x, y):
    # choose the smaller number
    if x > y:
        smaller = y
    else:
        smaller = x
    for i in range(1, smaller+1):
        if((x % i == 0) and (y % i == 0)):
            hcf = i
            
    return hcf


ch='y'
while(ch=='y' or ch=='Y'):
    print("1. Area of Square")
    print("2. Factorial")
    print("3. Swap")
    print("4. Leap Year")
    print("5. HCF")

    x=int(input("Enter choice : "))
    if(x==1):
        area_square()
    elif(x==2):
        n=int(input("Enter Number : "))
        factorial(n)
    elif(x==3):
        a=input("Enter First Number : ")
        b=input("Enter Second Number :")
        print("Before Swapping",a,b)
        a,b=swap(a,b)
        print("After Swapping",a,b)
    elif(x==4):
        year=int(input("Enter Year : "))
        leapYear(year)
    elif(x==5):
        x = int(input("Enter first number: "))
        y = int(input("Enter second number: "))
        hcf=HCF(x,y)
        print("The H.C.F. of", x,"and", y,"is", hcf)        
    else:
        print("Wrong Choice ")

    ch=input("Want to continue(Y/N) : ")

print("Successful!!")