FN 1
FN 1
Functions
• A function in Python is a group statements used to perform specific task
when it is called.
• Functions help break our program into smaller and modular chunks. As
our program grows larger and larger, functions make it more organized
and manageable.
• Built-in Functions
• User Defined Functions.
• Functions that are readily available to use are called Built-in functions
and there are many available in python for ex, print(), len(),etc..
• Functions that are defined by the user to do certain tasks are called
User defined functions.
Creating a Function
• A Function in Python is defined by the "def " statement followed by the
function name and parentheses. The basic syntax is
myname()
Output: Srinivas
def display():
print("Welcome to Python Programming")
display()
num(5) add(2,3)
name(‘Srinivas’) add(b=2,a=3)
a=10 print(a,b)
fun1(a)
print(a) Output: Error
Output:
20
10
Scope of variables in a Function
• We can make a function variable valid even outside the function by
declaring it as a global variable by using the key word ‘global’.
def fun1(a):
global b
b=20
print(a+b)
a=10;b=15
fun1(a)
print(b)
Output:
30
20
Passing variable length arguments
• We can pass arbitrary number of parameters to a function. The output
will be stored in the form of tuples.
Output:
([1, 2, 3],)
([1, 2, 3, 4],)
Use of Return statement
• The return statement is used to end the execution of the function call
and “returns” the result (value of the expression following
the return keyword) to the caller. The statements after the return
statements are not executed. If the return statement is without any
expression, then the special value None is returned. Return statement
can not be used outside the function. The syntax is
def fun():
statements
..
..
return [expression]
Use of Return statement
def fun1(p):
return p
a=10
fun1(a) #No output
print(fun1(a)) #Returns the function result
def greater(p,q):
if p>q:
return True
else:
return False
a=10
b=20
greater(a,b) #No output
print(greater(a,b)) #Returns the function result
Importing user defined functions
• We can use any user defined functions in other programs by using
‘import’ statement.