Lecture 3 - Python Functions
Lecture 3 - Python Functions
Python Function
Introduction
● In easy words, function is a code segment that does some specific tasks.
● It takes argument, does some calculation, and returns a result.
2
2+5 7
5
Return
Argument Calculation
Value
sazzad@diucse
Python Function
There are two types of functions-
● print( ), input( ), float( ), etc are built-in ● we can write functions based on our
functions requirement
● looking familiar? Yes, we have already ● we use def keyword to define a function
used them. ● like as built-in function, we can use user
● these functions are already defined functions multiple times
implemented in different libraries
● sometimes we need to import those
libraries to use these function
sazzad@diucse
Defining a Function
● A function begins with def keyword followed by Example of Defining Function
function name, a set of parentheses and a colon (:)
● Parentheses contains the parameters of the
function. If the parentheses are empty, that means
this function does not contain any parameters.
Here, def is the keyword
● Function may have return statement to return a
value. If there is no return statement, function sum is the function name
does not return anything. (a, b) are the parameters
● Statements after colon(:) with same indentation
are considered as function’s block. return c is the return statement
● Parameters and all the variables within a function c=a+b & return c both statement have started with
block are local variables same number of spaces. These spaces are known as
indentation. And for this these two statement are
considered as the function’s block.
sazzad@diucse
Calling a Function
Function Calling
A function can be called by the function
name followed by a set of parentheses.
A function can be called multiple times in a Here, sum( ) function does not have any return
statement
program. In the same way a single program
But square( ) function have return statement. That
can have multiple functions. why the return value is has been stored in sq
variable
sazzad@diucse
Different Parameter List
There can be three scenarios-
1. Function parameter can have multiple variables. Each variable should be separated by comma.
2. Function can have default parameter value. But if the function is called with new values, they will override
default values.
def fun(a=2, b="python", c=3.6):
3. Function can be defined without parameter. In that case, we do not need to pass any value while calling the
function.
def fun():
sazzad@diucse
What Happens When A Function Called
# function
def fun():
print("I am Python")
No more text, let’s see what happens
internally when we call a function.
# main code
print("Hello World")
fun()
sazzad@diucse
Scope of Variables
● Each identifier or variable is restricted by some
regions according to its declaration. This region is
known as scope. Global Scope
sazzad@diucse