Functions
Functions
1. Built in Functions
Built in Functions:
The functions which are coming along with Python software automatically,are called
built
in functions or pre defined functions
id()
type()
input()
eval()
sum()
Functions 1
The functions which are developed by programmer explicitly according to business
requirements ,are called user defined functions.
Syntax to create user defined functions:
#-------------------FUNCTIONS ---------------------
def function_name(parameters) :
def hello(name):
print("Hello ",name)
hello("Yashwanth")
Parameters
Parameters are inputs to the function. If a function contains parameters,then at the
time
of calling,compulsory we should provide values otherwise,otherwise we will get error.
Return Statement:
Function can take input values as parameters and executes business logic, and
returns
output to the caller with return statement
Types of arguments
def f1 (a,b):
f1(10,20)
a,b are formal arguments where as 10,20 are actual arguments
There are 4 types are actual arguments are allowed in Python.
1. positional arguments
2. keyword arguments
Functions 2
3. default arguments
positional arguments:
These are the arguments passed to function in correct positional order.
#Positional Argument
def add(a,b):
print("Sum of",a,"&",b,'is',a+b)
add(2,3)
The number of arguments and position of arguments must be matched. If we change the
order then result may be changed.
If we change the number of arguments then we will get error
2. keyword arguments:
We can pass argument values by keyword i.e by parameter name
#Keyword Arguments
def bday (name,wish):
print(year,wish,name)
Here the order of arguments is not important but number of arguments must be matched.
Note:
We can use both positional and keyword arguments simultaneously. But first we have to
take positional arguments and then keyword arguments,otherwise we will get
syntaxerror.
Functions 3
3. Default Arguments:
Sometimes we can provide default values for our positional arguments.
#Default Arguments
names(name=123)
If we are not passing any name then only default value will be considered.
def add(*n):
addition=0
for i in n :
addition=addition+i
add(1,2,3435,5654,56546,6456456,4565465)
Note:
We can mix variable length arguments with positional arguments
Note: After variable length argument,if we are taking any other arguments then we
should provide values as keyword arguments.
------------------------------
Functions 4
We can call this function by passing any number of keyword arguments. Internally these
keyword arguments will be stored inside a dictionary.
def display(**kwargs):
for k,v in kwargs.items():
print(k,"=",v)
display(n1=10,n2=20,n3=30)
n1=10
n2=20
n3=30
Handson
1. Declare a function add_two_numbers. It takes two parameters and it returns a
sum.
print(reverse_list([1, 2, 3, 4, 5]))
# [5, 4, 3, 2, 1]
print(reverse_list1(["A", "B", "C"]))
# ["C", "B", "A"]
Functions 5