0% found this document useful (0 votes)
3 views24 pages

Understanding Functions in Python

Functions in Python are reusable sub-programs that help break down complex tasks into manageable units, improving code maintainability and readability. They consist of a definition header and a body, with parameters that can be passed as arguments during function calls. Python supports built-in and user-defined functions, as well as various types of arguments including positional, default, and keyword arguments.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views24 pages

Understanding Functions in Python

Functions in Python are reusable sub-programs that help break down complex tasks into manageable units, improving code maintainability and readability. They consist of a definition header and a body, with parameters that can be passed as arguments during function calls. Python supports built-in and user-defined functions, as well as various types of arguments including positional, default, and keyword arguments.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

FUNCTIONS in

Python
What are Functions?

 Functions are sub-programs which perform tasks


which may need to be repeated.
 Function is a name unit of group of related
statements.
 Functions help break our program into smaller
units.

F(x)=2x2 # can be termed as a function. For function


F , x is the argument .ie. value given to it and 2x2 is
its functionality. For different values of x function f(x)
returns different results
F(1)=2 f(2)=8 F(3)=18
Why Functions?
 Reusability
 Reduces complexity of code.
 It reduces program sizes.
 Programs are easier to maintain.
 Programs are easier to understand.
Function Elements
There are two main elements of
functions:
[Link] the function. The function
definition can appear at the beginning
or end of the program file.
2. Invoke or call the function. This usually
happens in the body of the main()
function, but sub functions can call
other sub functions too.
Function definitions
A function definition has two major parts:
the definition header and the definition
body.
The definition header in Python has three
main parts:
 the keyword def
 identifier or name of the function
 parameters in parentheses.

def average(total, num):

Keyword Function name parameters


Function header- begins with keyword def
and ends with a : , specifies the name of
the function and its parameters.

Parameter- variables that are listed within


the parameter of a function header.

Function body- the block of statements


/indented statements beneath function
header that defines the action performed
by the function. It can or can not return the
values.
def greet (name): # not returning values
print(“Hello,” + name +” . Good afternoon!”)
A=input(“enter Name “)
greet(A) #function call

def sum(a,b): #returning values


return a+b
a=int(input(“enter first value”)
b=int(input(“enter Second value”)
c=sum(a,b) #function call
Print(“sum is “+c)
There are two types of function in python :
 built-in function –pre defined functions and are
always available for use
print(), input(), eval().
 User define function- these are defined by the
programmer.
def ddition(x,y):
sum = x + y
return sum
Note : Functions defined in modules-can only
be used when the corresponding module is
imported. ex. to use sin() function math module
should be imported.
Flow of execution in a function call
Refers to the order in which statement are
executed during a program run.
def func() : Last statement of the
……… function definition will
send the control back
return to where from the
function was called
#_main_
Function call will send the
control flow to the function func()
definition
print(……………..)
Whenever a function call statement is encountered, an
execution frame for the called function is created and the
control is transferred to it.
1. # to add two numbers
2. def calcsum( x,y): #ignored unless called.
3. sum=x+y
4. return sum
5. # _main_ #execution begins from here.
6. a=int(input('Enter first no.:'))
7. b=int(input('Enter second no. : '))
8. sum=calcsum(a,b)
9. print('Sum of 2 numbers is ', sum) 2 -- 6 -- 7 -- 8 2—3--4 8 -- 9

 Execution begins at the 1st statement. If it is a function definition then


python executes the function header line to check that it is proper
function header and ignores all function body.
 When a code line is a function call. It jumps to the function header
line and then to the 1st line of the function body and starts executing
it. If function ends with a return statement then control goes back to
function call statement and completes it.
 If the called function does not return any value then the control
jumps back to the line following the function call statement.
CALLING A FUNCTION
Once we have defined a function, we can call it
from another function, program or even the
Python prompt. A function call statement takes
the following form.

def cube(x):
res=x**3 #cube of value in x
return res #returns the computed value

<function name> (<value to be passed to argument>)

To call a function we simply type the function


name with appropriate parameters.
>>> cube(5)
 Passing literal as argument in function call.
cube (4)

 Passing variable as argument in function call.


num =10
cube(num)

 Taking input and passing the input as argument


in function call.
num=int(input(„Enter a no; „))
cube(num)

 Using function call inside another statement


print(cube(3)) # cube(3) will first get the computed
result and then printed
def my_func(): # function definition
x = 10
y = 20
print("Value of x inside function:", x)
print("Value of y inside function:", y)
x = 20
y = 10
my_func() # calling function
print("Value of x outside function:", x)
print("Value of y outside function:", y)
OUTPUT:
Value of x inside function: 10
Value of y inside function: 20
Value of X outside function: 20
Value of y outside function: 10
def my_func(): # function definition
x = 10
global y
y = 20
print("Value of x inside function:", x)
print("Value of y inside function:", y)
x = 20
y = 10
my_func() # calling function
print("Value of x outside function:", x)
print("Value of y outside function:", y)
OUTPUT:
Value of x inside function: 10
Value of y inside function: 20
Value of X outside function: 20
Value of y outside function: 20
Arguments and Parameters
Arguments (actual parameters)-the values
being passed as arguments.
Parameters(formal parameters)- the values
being received as parameters.
def power(x,y): # parameters
res=x**y
return res
X=2
Y=3
power(x,y) # function call 1-arguments
Power(x,4) # function call 2
Power(y,x) # function call3
Passing parameters
Function call must provide all the values as
required by function definition. Python supports
3 types of formal arguments/parameters:
 Positional argument
 Default argument
 Keyword argument # not in syllabus

Positional arguments- when the function call


statement must match the number and order of
arguments as defined in the function definition.
E.g
def check(a,b,c)
check(2,x,y)
check(5,3,2)
Default arguments-a parameter having a default
value in function header becomes optional in
function call. It may or may not have value for it.

def check(principal, time, rate=.10): # default value


si=(principal*time*rate)/100
return si
#_main_
p = float(input('Enter principal amount:'))
t=float(input('Enter time :'))
si=check(p, t)
print('Simple interest = ', si)
si=check(p, t, 0.15)
print('Simple interest = ', si)
The default values in function are considered only if
no value is provided for that parameter in the
function call statement.
In a function header, any parameter cannot have a
default value unless all parameters appearing on its
right have their default values.

def check(principal=10000, time, rate): #wrong

The parameter principal cannot have its default vale unless the
parameters on its right, time and rate have their default values.
Similarly , the parameter time cannot have its default value
unless the parameter on it right i.e . Rate has its default value.
Thus required parameter appears on its right
Keyword arguments –are the name argument with
assigned values being passed in the function call
statement.
Order of the argument can not be changed. To
have complete control and flexibility over the
Values sent as arguments for the corresponding
parameters. Python offers a way of writing function
calls where you can write any arguments.

check(time=12, principal =2000, rate=.10):


check(principal =2000, time=12, rate=.10):
check(rate=.10, principal =2000, time=12):
Rules for combining all three types of arguments
 An argument list must first contain positional argument
followed by any keyword argument.
 Keyword arguments should be taken from the required
arguments preferably.
 You can not specify a value for an argument more than
once.

Having a positional arguments after keyword arguments will


result into error.

def check (principal, cc, time=12, rate=0.10):


return principal*time*rate

Values for principal and cc can be provided either as positional


arguments or as keyword arguments but these values cannot
be skipped from the function call.
Returning values from functions
There are two types of functions in Python.
Functions returning values (fruitful function)
Functions not returning any value
Functions returning values
The value being returned can be one of the
following:
A literal a variable an expression

return 5 return 8+9 #literal being returned


return a # variable being returned
return a** 2 return (a+b+c)/2 #expression involving a variable
or literal being returned
The returned value of a function should be used in
the caller function/program inside an expression or a
statement
The returned value of a function should be used in the caller
function/program inside an expression or a statement .
def sum(x,y):
s=x+y
return s
a=int(input('Enter a number:'))
b=int(input('Enter a number:'))
ans=sum(a,b)
print(ans)
print(sum(3,4))
print(sum(4,5)> 6)

output
Enter a number:12
Enter a number:36
48
7
True
The return statement ends a function execution even if it is in the
middle of the function. A function ends the moment it reaches a return
statement.
def check (a=3):
return a*a
print(a) # this statement is unreachable because check () function
will end with return and control will never reach this statement.
Functions not returning value- the functions that perform some action
or do some work but do not return any computed value or final value
to the caller are called void functions
def hello():
print(„Hello‟)
def sum(a,b)
print(„Sum=„, a+b)
return
def replicate(): def replicate():
print('***') return(„***‟)
print(replicate()) print(replicate())
Scope of variables
Part(s) of program within which a name is legal and accessible, is
called scope of the name.
 Global Variable -A global variable is a variable defined in the main
program. Such variables are said to have global scope.

 Local Variable -A local variable is a variable within a function. Such


variables are said to have local scope

 Variables defined above the function is also a global variable


Z=2 #global variable
def sum(x,y):
s=x+y +z # x, y and s are local variables
return s
#_main_
a=int(input('Enter a number:')) # a, b and ans are global variables
b=int(input('Enter a number:'))
ans=sum(a,b)
print(ans)

You might also like