Function
In Python, a function is a group of related statements that performs a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and
larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
Creating Function/Function definition Syntax
def functionname(parameter):
function-suit
return <expression>
• def is keyword.
• The function block is started with colon(:)
• All same level block indentation remain at same indentation
• No. of parameter must be same in function definition and dunction calling
Function calling Syntax
Functionname(parameter)
#Program to add two numbers using function
def add(a,b): #Function definition
c=a+b
return c;
a=int(input("value of a="))
b=int(input("value of b="))
print("sum=",add(a,b)) #calling function add()
Output
value of a=23
value of b=56
sum= 79
Call by reference in Python
Mutable object parameters (arguments) in the Python language are passed by reference. It means if
you change what a parameter refers to within a function, the change also reflects back in the calling
function. For example −list are mutable because these are passing by reference.
def change_list(list1):
list1.append(20)
list1.append(30)
print("list inside function=",list1)
list1=[10,20,40,50]
change_list(list1);
print("list outside function",list1);
Output
list inside function= [10, 20, 40, 50, 20, 30]
list outside function [10, 20, 40, 50, 20, 30]
Call by value in python
In python immutable objects are passed by value. It means if you change what a parameter
refers to within a function, the change does not reflects back in the calling function. Example is string.
def change_string(str):
str=str+"Hello"
print("string inside function",str)
str1="Hi I am here"
change_string(str1)
print("string outside function",str1)
Output
string inside function Hi I am hereHello
string outside function Hi I am here
Function Arguments
You can call a function by using the following types of formal arguments −
1. Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.
Example
def simple_interest(p,t,r):
return(p*t*r)/100
p=float(input("Enter the principle amount"))
r=float(input("Enter the rate of interest"))
t=float(input("Enter the time in years"))
print("Simple interest=",simple_interest(p,r,t))
Output
Enter the principle amount10000
Enter the rate of interest5
Enter the time in years2
Simple interest= 1000.0
2. Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the
caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the
keywords provided to match the values with parameters.
Example
def simple_interest(p,t,r):
return(p*t*r)/100
print("Simple interest=",simple_interest(t=10,r=10,p=1900))))
Output
Simple interest= 1900.0
3. Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call
for that argument.
Example
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name="john")
Output
My name is john and age is 22
4. Variable-length arguments
Sometimes we may not know the number of arguments to be passed in advance. An asterisk (*) is
placed before the variable name that holds the values of all non keyword variable arguments. This tuple
remains empty if no additional arguments are specified during the function call.
Example
def printme(*names):
print("type of passed argument is",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("mohan","ram","shyam","sita")
Output
mohan
ram
shyam
sita
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends on where you
have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular identifier.
There are two basic scopes of variables in Python −
•Global variables
•Local variables
Global vs. Local variables
• Variables that are defined inside a function body have a local scope, and those defined outside have a global
scope.
• This means that local variables can be accessed only inside the function in which they are declared, whereas
global variables can be accessed throughout the program body by all functions. When you call a function, the
variables declared inside it are brought into scope.
Example of local and global variable
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them.
total = arg1 + arg2; # Here total is local variable.
print (("Inside the function local total :"), total)
return total;
# Now you can call sum function
sum( 10, 20 );
print(("Outside the function global total : "), total)
Output
Inside the function local total : 30
Outside the function global total : 0
Functions-”First class citizens”
First Class objects are those objects, which can be handled uniformly. First Class objects can
be stored as Data Structures, as some parameters of some other functions, as control structures
etc. A programming language is said to support first-class functions if it treats functions as first-
class objects.
properties of First Class Functions
• It is an instance of an Object type
• Functions can be stored as variable
• Pass First Class Function as argument of some other functions
• Return Functions from other function
• Store Functions in lists, sets or some other data structures.
Map()
It returns a list of result after applying the given function to each item of a given iterable list or tuple etc.
Example
def cube(x):
return x*x*x
list1=[1,2,3,4,5]
result=map(cube,list1)
print(list(result))
Output
[1, 8, 27, 64, 125]
Filter
It is used for element in sequence to be true of false.

functioninpython-1.pptx

  • 1.
    Function In Python, afunction is a group of related statements that performs a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes the code reusable. Creating Function/Function definition Syntax def functionname(parameter): function-suit return <expression> • def is keyword. • The function block is started with colon(:) • All same level block indentation remain at same indentation • No. of parameter must be same in function definition and dunction calling Function calling Syntax Functionname(parameter)
  • 2.
    #Program to addtwo numbers using function def add(a,b): #Function definition c=a+b return c; a=int(input("value of a=")) b=int(input("value of b=")) print("sum=",add(a,b)) #calling function add() Output value of a=23 value of b=56 sum= 79
  • 3.
    Call by referencein Python Mutable object parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −list are mutable because these are passing by reference. def change_list(list1): list1.append(20) list1.append(30) print("list inside function=",list1) list1=[10,20,40,50] change_list(list1); print("list outside function",list1); Output list inside function= [10, 20, 40, 50, 20, 30] list outside function [10, 20, 40, 50, 20, 30]
  • 4.
    Call by valuein python In python immutable objects are passed by value. It means if you change what a parameter refers to within a function, the change does not reflects back in the calling function. Example is string. def change_string(str): str=str+"Hello" print("string inside function",str) str1="Hi I am here" change_string(str1) print("string outside function",str1) Output string inside function Hi I am hereHello string outside function Hi I am here
  • 5.
    Function Arguments You cancall a function by using the following types of formal arguments − 1. Required arguments Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition. Example def simple_interest(p,t,r): return(p*t*r)/100 p=float(input("Enter the principle amount")) r=float(input("Enter the rate of interest")) t=float(input("Enter the time in years")) print("Simple interest=",simple_interest(p,r,t)) Output Enter the principle amount10000 Enter the rate of interest5 Enter the time in years2 Simple interest= 1000.0
  • 6.
    2. Keyword arguments Keywordarguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. Example def simple_interest(p,t,r): return(p*t*r)/100 print("Simple interest=",simple_interest(t=10,r=10,p=1900)))) Output Simple interest= 1900.0
  • 7.
    3. Default arguments Adefault argument is an argument that assumes a default value if a value is not provided in the function call for that argument. Example def printme(name,age=22): print("My name is",name,"and age is",age) printme(name="john") Output My name is john and age is 22
  • 8.
    4. Variable-length arguments Sometimeswe may not know the number of arguments to be passed in advance. An asterisk (*) is placed before the variable name that holds the values of all non keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Example def printme(*names): print("type of passed argument is",type(names)) print("printing the passed arguments...") for name in names: print(name) printme("mohan","ram","shyam","sita") Output mohan ram shyam sita
  • 9.
    Scope of Variables Allvariables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python − •Global variables •Local variables Global vs. Local variables • Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. • This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.
  • 10.
    Example of localand global variable total = 0; # This is global variable. # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them. total = arg1 + arg2; # Here total is local variable. print (("Inside the function local total :"), total) return total; # Now you can call sum function sum( 10, 20 ); print(("Outside the function global total : "), total) Output Inside the function local total : 30 Outside the function global total : 0
  • 11.
    Functions-”First class citizens” FirstClass objects are those objects, which can be handled uniformly. First Class objects can be stored as Data Structures, as some parameters of some other functions, as control structures etc. A programming language is said to support first-class functions if it treats functions as first- class objects. properties of First Class Functions • It is an instance of an Object type • Functions can be stored as variable • Pass First Class Function as argument of some other functions • Return Functions from other function • Store Functions in lists, sets or some other data structures.
  • 12.
    Map() It returns alist of result after applying the given function to each item of a given iterable list or tuple etc. Example def cube(x): return x*x*x list1=[1,2,3,4,5] result=map(cube,list1) print(list(result)) Output [1, 8, 27, 64, 125]
  • 13.
    Filter It is usedfor element in sequence to be true of false.