FUNCTIONS IN PYTHON
What is a function ?
•A set of code written to carry a specific task is called function
•It can be used repeatedly at different places inside a program
as and when required by the user.
•We can define number of functions inside a program
Advantages of function
•Decomposing complex problems into simpler pieces
•Reusability of code
•Reduces program complexity
•increases program readability
•Reduces chance of error
•Improving clarity of the code
Types of function
1. Built in function
2. Functions defined in the modules
3. User defined function
•Built in function - These functions are already available in
python. it is available in python standard library and not
required to define the module
example:-max(), min(), sum(), type(), id(),int(), float(),
str(),list(),tuple(), dict(),eval(), input(), range(),len() etc
•Functions defined in the modules -These functions are
defined in a particular module. it can not be used without
defining the module inside the program using import
keyword.
example:- random(), randint(), randrange(), sqrt()
•User defined function – functions are defined by the user.
Types of user defined function
Defining a Function
A function in Python is defined using def keyword as given below:
def <function name > ([parameters]):
function executable statement(s)
[ return statement ]
•Keyword def that marks the start of the function header.
• A function name to uniquely identify the function. Function
naming follows the same rules of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a
function. They are optional.
• A colon (:) to mark the end of the function header.
• One or more valid python statements that make up the
function body. Statements must have the same indentation
level (usually 4 spaces).
• An optional return statement to return a value from the
function.
Function header: The Header of a function specifies the name of the
function and the name of each of its parameters. It begins with the
keyword def.
Parameters: Variables that are listed within the parenthesis of a
function header.
Function Body: The block of statements to be carried out, ie the action
performed by the function.
Indentation: The blank space needed for the python statements. (four
spaces convention)
Types of user defined function
1. No Argument No return
2. With Argument No return
3. No Argument with return
4. With Argument with return
1. No Argument No return
def show(): #defining function
print(“I am in show function”)
show() # calling function
*************************
def Sum(): #defining function
a= int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
s=a+b
print (“The Sum of inputted Numbers is:”, s)
Sum() # calling function
print(“ Sum() Function Executed”)
2. With Argument No return
def Sum(a,b): #defining function
c=a+b
print(“The Sum of inputted Numbers is:”, c)
num1=int (input(“Enter First Number”))
num2= int (input(“Enter Second Number”))
#main
Sum(num1,num2) #calling function
Remember: The variable in main program are differ from the
variable in function definition i.e. a and b should be x and y.
In this scenario the variable passed (num1,num2)will be
called argument,
and when it replace with the variable defined in the
function will be called as parameter.
3. No Argument with return
def Sum(): #defining function
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
return c
#main
s= Sum() # calling function
print (“The Sum of inputted Numbers is:”, s)
Note: As return does not show the result we have to store
the returned value on another variable s
4. With Argument with return
def Sum(a,b): #defining function
c=a+b
return c
#main
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
s= Sum(a,b) #calling function
print (“The Sum of Numbers is:”, s)
Parameters and Arguments in Function
Parameters are the values provided at the time of function
definition.
Example:- def SI(p, r, t) #defining function
Arguments are the values passed while calling a function.
Example:- SI(p, r, t) # calling function
Types of Arguments:
•Positional Arguments:
•Default Arguments:
•Key Word Arguments:
•Variable Length Arguments:
Positional Arguments: Arguments passed to a function in correct
positional order and no. of arguments must match with no. of
parameters required.
Actual argument and formal argument
The argument which is passed in a function call is called actual
argument.
The argument which is defined at the time of defining function is
called formal parameter
def sum(a,b) : #defining function # a and b are formal parameter
#code
sum(x,y) #calling function
x and y are called actual argument it sends value to formal paremeter
No of argument in actual argument and formal parameter should be
matched
Default Arguments: Assign default to value to a certain parameter, it is
used when the user knows the value of the parameter, default values
are specified in the function header.
It is optional in the function call statement. If not provided or
argument is missing in the function call statement then the default
value is considered.
Default arguments must be provided using = sign and specified from
right to left in function header.
Ex:-def cal_discount(amt=500,rate=10)cal_discount(rate=10,amt=500)
Keyword Arguments: Keyword arguments are the named arguments
with assigned values being passed in function call statement, the user
can combine any type of argument. Exmaple :- Sum(a=10,b=20)
Variable Length Arguments: It allows the user to pass as many
arguments as required in the program. Variable-length arguments are
defined with * symbol. Exmaple :- Def disp(name*)
There are two kinds of scopes:
Local Variable:
•Local variable is defined inside body of the function
definition.
•The value of local variable is availble inside the function
where it is declared
•The scope of the variable is limited to the function inside
which it is defined.
•It can not be accessed out side the function.
Example:-
def sum():
a=10
b=20 # a and b are called local variable
print(a,b)
Global Variables :
In Python, a variable declared outside of the function or in
global scope is known as a global variable. This means that a
global variable can be accessed inside or outside of the
function.
# declare global variable
message = 'Hello'
def greet(): # declare local variable
print('Local', message)
greet()
print('Global', message)
Output:-
Local Hello
Global Hello
Non Local Variable:
In Python, nonlocal variables are used in nested functions
whose local scope is not defined. This means that the variable
can be neither in the local nor the global scope.
We use the nonlocal keyword to create nonlocal variables. For example,
# outside function
def outer():
message = 'local‘
# nested function
def inner():
# declare nonlocal variable nonlocal message
message = 'nonlocal'
print("inner:", message)
inner()
print("outer:", message)
outer()
Note : If we change the value of a nonlocal variable, the changes appear
in the local variable.
Use of global keyword :-
In Python, the global keyword allows us to modify the
variable outside of the current scope.
It is used to Change Global Variable From Inside a Function
using global
IF we want the redefine the local variable inside a function as
global then global keyword is used.
In other words it is used to create a global variable and make
changes to the variable in a local context.
# global variable ttl=50
c=1 def add(x, y):
Print(c ) global ttl
def add(): ttl=x+y
# use of global keyword print ("modifying global
global c variable in function")
# increment c by 2 print ("total=",ttl)
c=c+2 add(10,20)
print(c) print ("ttl is global variable")
add() print ("total=",ttl)
print( c ) Output :- 30
Output:-1 30
3
3
Function with return
Passing a List as an Argument
You can send any data types of argument to a function (string, number,
list, dictionary etc.), and it will be treated as the same data type inside
the function.
E.g. if you send a List as an argument, it will still be a List when it reaches
the function:
def my_function(fr): # defining functin using list as argument
for x in fr:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits) # calling functin using list
Passing string as function argument
# Python program to pass a string to the function
# function definition: it will accept a string parameter and print it
def printMsg(str):
# printing the parameter
print str
# Main code
# function calls
printMsg("Hello world!")
printMsg("Hi! I am good.")
We can pass the string variable as function argument also
st=input(“enter any string “)
printMsg(st)
Output :-
Hello world!
Hi! I am good.
# function definition: it will accept a string parameter and return
number of vowels
def countVowels(str):
count = 0
for ch in str:
if ch in "aeiouAEIOU":
count +=1
return count
# Main code
# function calls
str = "Hello world!"
print("No. of vowels are”, countVowels(str))
str = "Hi, I am good."
print("No. of vowels are “, countVowels(str))
Output:-
No. of vowels are 3 in "Hello world!"
No. of vowels are 5 in "Hi, I am good."