Function in Python
Function in Python
PASSING PARAMETERS
1. Default parameter values:
Defining the value in the def
Eg:
def function (a,b, c=10) default parameters
2. Keyword argument:
Defining the value during the function call
Eg:
def sum(a,b):
x=a+b
y=a-b
print(“sum is:”,x)
print(“difference is:”,y)
sum(a=10, b=6)
sum(a=5, b=8)
Eg:
def sum(a,b):
x=a+b
print(“sum is:”,x)
sum(a=10, b=6)
RETURNING VALUES FROM FUNCTION
1. NON-VOID FUNCTIONS:
It is used to do specific task. It returns the value on completion of
task. It is also called fruitful function.
Eg:
def work( ):
print(“HELLO”)
return “HELLO”
def sum(a,b):
x=a+b
print(“sum is:”,x)
sum(a=10, b=6)
SCOPE OF VARIABLES
A variable defined inside a function cannot be accessed outside.
Scope of variables shows the area where the variables can be used.
There are two types of scope of variables:
1. LOCAL VARIABLE (LOCAL SCOPE):
A variable that is defined inside any function or block is known as local
variable.
It is accessed only by the statements of the function
Eg:
def msg( ):
message=” hello” #local variable defined inside function
print( message)
msg( )
Error program:
def msg( ):
message=” hello” #local variable defined inside function
print( message)
msg( )
print(message) # this will cause an error because a local variable
cannot be accessed while calling function
2. GLOBAL VARIABLE( GLOBAL SCOPE):
A variable that is defined outside of all function or block is known as
local variable.
It is accessed by all the function without declaring inside the body.
Eg:
total=0 #global variable
def sum(a,b):
total=a+b
print(“sum is “, total)
sum(a=int(input(“enter the number”)), a=int(input(“enter the
number”))
print(“outside sum”, total)