Search This Blog

Wednesday, 15 December 2021

Functions in Python

 

Python Functions

simple web creator

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.

As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions

Defining a Function

1

Keyword def is used to start and declare a function. def specifies the starting of function block.

2

def is followed by function-name followed by parenthesis.

3

Parameters are passed inside the parenthesis. At the end a colon is marked.

4

Python code requires indentation (space) of code to keep it associate to the declared block.

5

The first statement of the function is optional. It is documentation string of function.

6

Following is the statement to be executed.

7

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

def functionname( 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.

Example :

def sum(a,b) :
  c=a+b
  return c

Calling a Function

To execute a function it needs to be called. This is called function calling. Function Definition provides the information about function name, parameters and the definition what operation is to be performed. In order to execute the function definition, we need to call the function.

Example :

def swap(x, y):
    temp = x;
    x = y;
    y = temp;
    return

x = 2
y = 3
swap(x, y) #call fun
print(x)
print(y)

output of above example  :

2
3

Python Function return Statement

return[expression] is used to return response to the caller function. We can use expression with the return keyword. send back the control to the caller with the expression.In case no expression is given after return it will return None.In other words return statement is used to exit the function definition.

def sum(a,b):
    print("Adding the two values")
    print("Printing within Function")
    print(a+b)
    return a+b

def msg():
    print("Hello")
    return

total=sum(10,20)
print('total : ',total)
msg()
print("Rest of code")

output of above example  :

Adding the two values
Printing within Function
30
total : 30
Hello
Rest of code

Function Argument and Parameter

There can be two types of data passed in the function.

  • The First type of data is the data passed in the function call. This data is called arguments.
  • The second type of data is the data received in the function definition. This data is called parameters.

Arguments can be literals, variables and expressions. Parameters must be variable to hold incoming values.

Alternatively, arguments can be called as actual parameters or actual arguments and parameters can be called as formal parameters or formal arguments.

# x is parameters or formal parameters or formal arguments.
def evenOdd( x ):
    if (x % 2 == 0):
        print("even")
    else:
        print("odd")

# Driver code
evenOdd(2)   # here 2 is argument or actual perameter
evenOdd(3)   #3 is argument or actual perameter

output of above example  :

even
odd

Function Arguments

You can call a function by using the following types of formal arguments −

  • Required arguments 
  • Keyword arguments
  • Default arguments
  • Variable-length arguments
  • 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
def cube(x):
    "This x a passed num value into this function, return cube of x"
    y=x*x*x;
    return y



# Now you can call cube function
z=cube(2)  #required to pass argument
print(z)

output of above example  :

8
  • 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.

def remainder(dividend,divisor):
    x=dividend%divisor
    return x

rem = remainder(divisor = 3, dividend = 10) #keyword argument
print("remainder of 10/3 : ",rem)

output of above example  :

remainder of 10/3 : 1
  • 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. The following example gives an idea on default arguments, it prints default age if it is not passed 
def emp_data(name,emp_id,age,company = "self employee"):
    print("Details of: ",name)
    print("Emp Id : ",emp_id)
    print("Age : ",age)
    print("Company : ",company)


#call emp_data fun
emp_data("Vishal",101,21,"ApkZube")
print("-----------------------")
emp_data("Jignesh",102,22)

output of above example  :

Details of: Vishal
Emp Id : 101
Age : 21
Company : ApkZube
-----------------------
Details of: Jignesh
Emp Id : 102
Age : 22
Company : self employee
  • 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 given below 

def functionname([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 nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −

def printinfo( 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 )

output of above example  :

Output is:
10
Output is:
70
60
50

Python Anonymous Function (Lambda Function)

These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

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

Syntax : 

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

Example :

#Normal Function definition is here
def square(x):
    return x*x

# anonymous function
sqr = lambda x: x*x

#Calling square function
print("Square of number is",square(10)) #call normal function
print("Square of number is",sqr(2)) #call anonymous function

output of above example  :

Square of number is 100
Square of number is 4

Scope of Variable

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 - Variable defined outside the function is called Global Variable. Global variable is accessed all over program thus global variable have widest accessibility.
  • Local variables - Variables declared inside a function body is known as Local Variable. These have a local access thus these variables cannot be accessed outside the function body in which they are declared.

Example :

x=50

def print_data():
    x=5
    y=10
    print("(x,y):(",x,",",y,")")

print_data() #(x,y):( 5 , 10 )
print("Global x :",x) #Global x : 50
print("Local y : ",y) #y is local veriable - throw NameError

output of above example  :

(x,y):( 5 , 10 )
Global x : 50
Traceback (most recent call last):
  File "main.py", line 10, in
    print("Local y : ",y) #y is local veriable - throw NameError
NameError: name 'y' is not defined

No comments:

Post a Comment

how to implement YOLOv3 using Python and TensorFlow

Object Detection with YOLOv3 Introduction YOLOv3 (You Only Look Once version 3) is a real-time object detection algorithm that can detect ob...