FUNCTIONS
If a group of statements is repeatedly required then it is not
recommended to write these statements everytime separately.
We have to define those statements as a single unit and we can call that
unit any number of times. This unit is nothing but a function.
The main advantage of functions is code Reusability.
Note: In other languages functions are known as
methods,procedures,subroutines etc
Python supports 2 types of functions
1. Built in Functions
2. User Defined Functions
1. Built in Functions:
The functions which are coming along with Python software
automatically,are called built-in functions or pre defined functions
Eg:
id()
type()
input()
eval()
etc..
2. User Defined Functions:
The functions which are developed by programmers explicitly according to
business requirements ,are called user defined functions.
Syntax to create user defined functions:
def function_name(parameters):
""" doc string"""
----
-----
return value
Note: While creating functions we can use 2 keywords
1. def (mandatory)
2. return (optional)
Program 1;
def greetings():
print("Hello")
greetings()
greetings()
greetings()
greetings()
greetings()
#Function Type 1:
#Function without arguments and without return type
def add():
a = 10
b = 20
print(a+b)
add()
#Function Type 2:
#Functions with arguments and without return type
def add(a,b):
print(a+b)
add(123,456)
#Function Type 3:
#Functions without arguments and with return type
def add():
a = 100
b = 200
return a+b
result = add()
print(result)
#Function Type 4:
#Functions with arguments and with return type
def add(x, y):
return x+y
result = add(23,45)
print(result)
#Functions with multiple return values
def calculator(a,b):
sum = a+b
diff = a-b
product = a*b
quo = a/b
return sum, diff,product,quo
result = calculator(1234,50)
for i in result:
print(i)
#functions with variable arguments
def sum(*n):
total = 0
for i in n:
total = total + i
print("The Sum of Given Number is ", total)
sum()
sum(10,20)
sum(123,456)
sum(10,20,30,40,50)
def greetings(name,msg="Advanced Python COurse"):
print("Hello", name, "Welcome to",msg)
greetings('Raman','Python Course')#Positional Arguments
greetings(msg='Java Course',name='Sam')#Named Arguments
greetings('Tom')#Default Aruguments