Functions are used to reusability of the code. In python we declare it with a keyword def. The syntax is
def function_name(arguement):
statement_1
statement_2
Let us see the example to add two numbers using function.
def add(a,b):
return a+b
x = add(10,20)
print(x)
30
Local and Global Scope
def change(a):
a = 20
print(a)
a = 2
print(“The value of ‘a’ before the function call “, a)
print(“The value of the in the function “)
change(a)
print(” The value of ‘a’ after the function call “, a)
Output:-
The value of ‘a’ before the function call 2
The value of ‘a’ in function 20
The value of ‘a’ after the function call 2
The value of the ‘a’ does not change. This is because the scope of the variable is within the function. To extent the scope of the variable we can use the keyword global.
def change(a):
global a = 20
print(a)
a = 2
print(“The value of ‘a’ before the function call “, a)
print(“The value of the in the function “)
change(a)
print(” The value of ‘a’ after the function call “, a)
Output:-
The value of ‘a’ before the function call 2
The value of ‘a’ in function 20
The value of ‘a’ after the function call 20
Default Arguement
def show(a, b=-1):
if a>b
print(“a is greater”)
else
print(“b is greater”)
show(10)
show(10,20)
In above program, we assigned the value of the ‘b’ as -1 because to set the least possible value. The output will be.
a is greater
b is greater
Keyword argument
def assign(a, b=10, c=20):
print((“a is “, a, “b is “, b, “c is “, c)
assign(2)
assign(1, b=2)
assign(1, b=2, c=3)
It is important that if the arguement is declared with a value then any arguement cannot be assigned. Like def(a, b=10, c) throws an error.
Output:-
a is 2 b is 10 c is 20
a is 1 b is 2 c is 20
a is 1 b is 2 c is 3