Python Function
- Group of statements that together perform a specific task.
- It defines the behavior of a class
- Implementation of variables
- Function can have a list of formal parameters and may or may not a return value
- In python, the function can be created with help of def keyword
TYPES OF FUNCTION
- Python supports two types of functions. They are:
- Built-in function or pre-defined function or library function
- User defined function.
1. Pre-defined function (Built-in function)
- It is already created by developer and added in python library
- Once python modules are imported, then user can access its predefined functions in the code
- No need to provide any implementation (definition) for this pre-defined function. Because its definition is already created and attached with corresponding python modules.
- Example
- print(), input(), etc, …
2. User defined function
- Here function is created by programmer or user
- The def keyword is used to create one or more number function in python language
- The keyword def is used to start and declare a function. A colon (:) operator must be marked at the end of function declaration
- It is called by using its name.
INVOKING FUNCTION
- Process of activating a method is called invoking or calling.
- In python, the function is called by using its name.
I. FUNCTION WITH NO ARGUMENTS
(test.py)
1. SOURCE CODE
# creating a function
def info():
print (“Welcome to Chennai”)
# calling a function
info()
2. OUTPUT
II. FUNCTION WITH ARGUMENTS
(test.py)
1. SOURCE CODE
# creating a function
def add(x,y):
c=x+y
print(“Sum is : “,c)
# calling a function
add(10,5)
2. OUTPUT
RETURN STATEMENT
- Like c++/java, python supports return statement
- The return expression is used to send the output from called function to calling function (caller function)
- It will return nothing, if no expression is given after the return statement
- Unlike c++/java/c#, python returns multiple values which are types of tuples.
III. FUNCTION WITH ARGUMENTS AND RETURN STATEMENT
(test.py)
1. SOURCE CODE
# creating a function
def add(x,y):
c=x+y
return c
# calling a function
rs=add(7,6)
print(“Add is : “,rs)
2. OUTPUT