SlideShare a Scribd company logo
1 of 24
Working with Functions
Function is a subprogram that acts on data and often returns a
value.
●Advantages of Function
1.Program development made easy and fast
2.Program testing becomes easy- corrections need to be made only at one place
3.Code sharing becomes possible
4.Code re-usability increases
5.Increases program readability
●Python Function Types
1. Built-in functions-> predefined, always available ( len(),type(),input() )
2. Function defined in modules-> predefined in particular module, need to
import modules. ( ceil() in math, randint() from random)
3. User defined functions-> defined by programmer.
Structure of User Defined Functions
Function Header # name of function and its parameters
Parameters # variables that are listed within the parentheses of function header
Function Body # block of statements indented.
Indentation # All statements within same block have same indentation.
(usually 4 spaces in the beginning of statement)
Non-void Function
Void Function
1. def sumofmultiples(n): OR def
sumofmultiples(n):
s=n*1 + n*2 + n*3
s=n*1 + n*2 + n*3 return s
Creating & Calling a Function (user defined)
argument:- values being passed are actual arguments (appears in function call)
Parameters:- values being received as parameters are formal (appears in function header)
A function is defined using the def keyword in python.E.g. program is given below.
1. def my_own_function(d): #Function header
2. print("Hello from a function")
#Function Body
return d # Function may/maynot
have return statement
3. print("hello before calling a function") #main function/ high level
4. r=my_own_function(4) #function call
5. print("hello after calling a function")
Flow of execution of program:
1. #Python Program to add two number through function
2. def add2number2(x, y): # here x, y are parameters
3. r=x+y
4. return r
5.
6. # take input from the user
7. num1 = int(input("Enter first number: "))
8. num2 = int(input("Enter second number: "))
9. Result=add2numbers(num1, num2) # here num1, num2 are Arguments
10. print("The sum. of", num1,"and", num2,"is",Result)
1. # Python Program to find the factorial of a given number
2. def factorial(n): # parameters=
3. fact = 1 # local variable=fact
4. for i in range(1,n+1):
5. fact = fact * i
6. return fact
7. print ("The factorial of 5 is : ",end="")
8. print (factorial(5)) #arguments=
Python Supports three types of formal parameters
1. Positional parameters (Required parameters)
2. Default parameters appears
in Function Header
3. Arbitrary parameters/ Variable length parameters
4. Named parameters (Keyword parameters)
appears in Function Call
1. def check(a,b,c):
2. s=a+b+c
3. print(s)
Default Parameter (Function
header)
def Check (a=3,b=7,c=100) :
s=a+b+c
print(s)
x,y,z=10,20,30
Check(x,y,z)
Check(x,y)
Check(x)
Check()
Named Parameter (Function call)
def si(prin=2000,time,rate=0.06):
return prin*time*rate
Si(9000,5)
Si(prin=9000,time=7,rate=0.04)
Si(rate=9.0,prin=1000,time=6.1)
Si(4000,prin=3000,time=8)
Arbitrary arguments / Variable-length Arguments
Sometimes you may need more arguments to process function then you mentioned in the definition(when you are passing . If we don’t know in advance
about the arguments needed in function, we can use variable-length arguments also called arbitrary arguments.
For this an asterisk (*) is placed before a parameter in function definition which can hold non-keyword variable-length arguments and
a double asterisk (**) is placed before a parameter in function which can hold keyword variable-length arguments.
If we use one asterisk (*) like *var, then all the positional arguments from that point till the end are collected as a tuple called ‘var’ and
if we use two asterisks (**) before a variable like **var, then all the positional arguments from that point till the end are collected as a dictionary called
‘var’.
def greet(*args):
# This function greets all the person in the names tuple.
# names is a tuple with arguments
for n in args:
print("Hello", n)
#Calling the function
greet("Monica", "Luke", "Steve", "John")
Output
Hello Monica
Hello Luke
Hello Steve
Hello John
def display(*args, **kwargs):
"""This function display all persons in names tuple.
and all keyword arguments as dictionary"""
for items in args:
print (items)
for items in kwargs.items():
print (items)
#Calling the function
display(‘John','Mary','Nina',Mohan='LA',Seema='NY',
Reena='DC‘)
Variable’s Scope in function
There are three types of variables with the view of scope.
1. Local variable – accessible only inside the functional block where it is declared.
2. Global variable – variable which is accessible among whole program using global keyword.
3. Non local variable – accessible in nesting of functions, using nonlocal keyword. Used in nested functions.
Global-Local Environment
Global Environment
For main()
S -> “I love World”
Local Environment
For fun()
S -> “I Love India”
Non Local Variable Program
1.def myfunc1():
2. x = "John"
3. def myfunc2():
4. global x
5. x = "hello"
6. myfunc2()
7. return x
8.X=“SEEMA”
9.print(myfunc1())
1.def myfunc1():
2. x = "John"
3. def myfunc2():
4. nonlocal x
5. x = "hello"
6. myfunc2()
7. return x
8.
9.print(myfunc1())
Global Environment
For main()
X->SEEMA
Local Environment
For myfunc1()
X -> “Hello”
LOCAL ENV FOR
MYFUNC2()
x-=“hello”
Variable’s Scope in function
Possible combinations of Returning values from functions
1. non-void functions without arguments
2. non-void functions with some arguments
3. void functions without arguments
4. void functions with some arguments
Returning multiple values from funtion
1. def squared(x,y,z) :
return x*x, y*y, z*z
t=squared(1,2,3) # t is tuple
a,b,c=t
print(t)
2. def squared(x,y,z) :
return x*x, y*y, z*z
a,b,c=squared(1,2,3) # unpack received tuple in a,b,c
t= (a,b,c)
print(t)
1
4
9
Write Flow of Execution of program (trace the program).
Draw the entire environment, for all variables at the time line 10 is being executed.
Predict the output of the program
1. def calcSum(a,b,c):
2. s=a+b+c
3. return s
4. def average( x,y,z):
5. sm=calcSum(x,y,z)
6. return sm / 3
7. n1=int(input(“Number 1:”))
8. n2=int(input(“Number 2:”))
9. n3=int(input(“Number 3:”))
10.print(“Average of these number is”, average(n1,n2,n3))
Flow of execution of program:
1-4-7-8-9-10-4-5-1-2-3-5-6-10
Global Environment
n1 -> 11
n2 -> 22
n3 -> 33
22.0
Local Environment
For average()
X -> 11
Y -> 22
Z -> 33
Sm -> 66
66/3 -> 22.0
Local Environment for
calcSum()
A -> 11
B -> 22
C-> 33
S -> 66
Lifetime of Variable
Local Variable Global Variable
It is a variable which is declared within
a function or within a block.
It is a variable which is declared outside
all the functions.
It is accessible only within a
function/block in which it is declared.
It is accessible throughout the program.
Passing Immutable Type value to a Function
1. def func1( x):
2. print(“Inside functions my value is :”,x)
3. x=x ** 2
4. print(“Now my value is : “, x)
5. n=3
6. print(“Calling func1() by passing ‘n’ with value :”, n)
7. func1(n)
8. print(“Back from func1(). Now value of ‘n’ is :, n )
# Draw environments and predict the outputs
Conclusion-
Changes in immutable type are not reflected in the
caller function at all.
Output-
Calling func1() by passing ‘n’ with value
:3
Inside functions my value is :3
Now my value is : 9
Conclusion-
Changes in mutable types are reflected in caller function if its name is not
assigned a different variable or datatype
1. def func1(Rlist):
2. print(“Inside function”)
3. print(“Received List: “, Rlist)
4. Rlist[0] += 5
5. print( “List within called function
after change: “,Rlist)
6. Slist=[25]
7. print(“List before function call:”,Slist)
8. func1(Slist)
9. print(“List after function call :”, Slist)
Rlist Rlist[0]
Rlist
Rlist[0]
Slist Slist[0]
25
25 +5
Passing Mutable Type value to a function ( making changes in place)
1. def func1(Rlist) :
2. print(“Inside Function”)
3. print(“Received List :”,Rlist)
4. Rlist.append(100)
5. Rlist.extend ( [ 11,13,17] )
6. print(“List after adding some elements:”,
Rlist)
7. Rlist.remove(13)
8. print(“List after removing one element:”,
Rlist)
9. Slist=[25]
10.print(“List before function call : “,Slist)
11.func1(Slist)
12.print(“List after function call : “,Slist)
Rlist / Rlist[0]
OR Slist/ Slist[0]
Rlist
Rlist
Rlist
Slist / Slist[0]
Conclusion-
Changes in mutable types are reflected in caller function if it is not assigned a different variable or datatype
25 100 11 13 17
25 100
25 100 11 17
Passing Mutable Type value to a function ( making changes in place)
1. def func1(Rlist) :
2. print(“Inside Function”)
3. print(“Received List :”,Rlist)
4. Newlist=[1,2,3]
5. Rlist=Newlist
6. Rlist.append(100)
7. Rlist.extend ( [ 11,13,17] )
8. print(“List after adding some elements:”, Rlist)
9. Rlist.remove(13)
10. print(“List after removing one element:”, Rlist)
11. Slist=[25]
12. print(“List before function call : “,Slist)
13. func1(Slist)
14. print(“List after function call : “,Slist)
Rlist / Rlist[0]
Newlist =[1,2,3]
Rlist =Newlist
Rlist .append(100)
Rlist.extend([11,13,17])
Rlist
Rlist.remove(13)
Slist / Slist[0]
Conclusion-
Changes in mutable types are not reflected in caller function if it is assigned a different variable or datatype within
function definition
1 2 3
1 2 3
1 2 3 100
1 2 3 100 11 13 17
1 2 3 100 11 17
Resolving scope of a Name (LEGB rule)
The LEGB rule is a kind of name lookup procedure, which determines the order in which Python looks up names.
Python scopes are implemented as dictionaries that map names to objects. These dictionaries are commonly called namespaces. These
are the concrete mechanisms that Python uses to store names. They’re stored in a special attribute called __dict__.
(import math and show how to check variables in a module like math.__dict__)
L – Local Environment / Namespace- inside function
E – Enclosing Environment / Namespace -inside nested functions nonlocal scope
G - Global Environment / Namespace- inside main/module scope
B - Built-in Environment / Namespace - from anywhere in program
(keywords, built in functions and
attributes)
Otherwise Python would report error.
B G E L
Lambda Function
Python allows us to not declare the function in the standard manner, i.e., by using the def keyword. Rather, the anonymous functions are declared by
using lambda keyword. However, Lambda functions can accept any number of arguments, but they can return only one value in the form of
expression.
Syntax:- lambda arguments : expression
Example
1.
x = lambda a:a+10 # a is an argument and a+10 is an expression which got evaluated and returned.
print("sum = ",x(20))
2.
x = lambda a,b:a+b
# a and b are the arguments and a+b is the expression which gets evaluated and returned.
print("sum = ",x(20,10))
3.
#the function table(n) prints the table of n
def table(n):
return lambda a:a*n; # a will contain the iteration variable i and a multiple of n is returned at each function call
n = int(input("Enter the number?"))
b = table(n) # the entered number is passed into the function table. b will contain a lambda function which
# is called again and again with the iteration variable i
for i in range(1,11):
print(n,"X",i,"=",b(i)) #the lambda function b is called with the iteration variable i,

More Related Content

What's hot

Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguageSamir Chekkal
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming languageSQLI
 
The Ring programming language version 1.5.4 book - Part 32 of 185
The Ring programming language version 1.5.4 book - Part 32 of 185The Ring programming language version 1.5.4 book - Part 32 of 185
The Ring programming language version 1.5.4 book - Part 32 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 23 of 88
The Ring programming language version 1.3 book - Part 23 of 88The Ring programming language version 1.3 book - Part 23 of 88
The Ring programming language version 1.3 book - Part 23 of 88Mahmoud Samir Fayed
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
The Ring programming language version 1.5.2 book - Part 20 of 181
The Ring programming language version 1.5.2 book - Part 20 of 181The Ring programming language version 1.5.2 book - Part 20 of 181
The Ring programming language version 1.5.2 book - Part 20 of 181Mahmoud Samir Fayed
 
4. python functions
4. python   functions4. python   functions
4. python functionsin4400
 
The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202Mahmoud Samir Fayed
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210Mahmoud Samir Fayed
 
Storage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageStorage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageJenish Bhavsar
 

What's hot (20)

Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 
The Ring programming language version 1.5.4 book - Part 32 of 185
The Ring programming language version 1.5.4 book - Part 32 of 185The Ring programming language version 1.5.4 book - Part 32 of 185
The Ring programming language version 1.5.4 book - Part 32 of 185
 
The Ring programming language version 1.3 book - Part 23 of 88
The Ring programming language version 1.3 book - Part 23 of 88The Ring programming language version 1.3 book - Part 23 of 88
The Ring programming language version 1.3 book - Part 23 of 88
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
The Ring programming language version 1.5.2 book - Part 20 of 181
The Ring programming language version 1.5.2 book - Part 20 of 181The Ring programming language version 1.5.2 book - Part 20 of 181
The Ring programming language version 1.5.2 book - Part 20 of 181
 
4. python functions
4. python   functions4. python   functions
4. python functions
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181
 
The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210
 
Storage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageStorage classes arrays & functions in C Language
Storage classes arrays & functions in C Language
 

Similar to Python functions

Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdfpaijitk
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfDaddy84
 
The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202Mahmoud Samir Fayed
 
Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdfpaijitk
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxKhurramKhan173
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180Mahmoud Samir Fayed
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfTeshaleSiyum
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdfTeshaleSiyum
 

Similar to Python functions (20)

Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
functions
functionsfunctions
functions
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
 
The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 

More from ToniyaP1

Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear listsToniyaP1
 
Python library
Python libraryPython library
Python libraryToniyaP1
 
Python algorithm efficency
Python algorithm efficencyPython algorithm efficency
Python algorithm efficencyToniyaP1
 
Python data file handling
Python data file handlingPython data file handling
Python data file handlingToniyaP1
 
Python recursion
Python recursionPython recursion
Python recursionToniyaP1
 

More from ToniyaP1 (6)

Numpy
NumpyNumpy
Numpy
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
 
Python library
Python libraryPython library
Python library
 
Python algorithm efficency
Python algorithm efficencyPython algorithm efficency
Python algorithm efficency
 
Python data file handling
Python data file handlingPython data file handling
Python data file handling
 
Python recursion
Python recursionPython recursion
Python recursion
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 

Python functions

  • 1.
  • 2. Working with Functions Function is a subprogram that acts on data and often returns a value. ●Advantages of Function 1.Program development made easy and fast 2.Program testing becomes easy- corrections need to be made only at one place 3.Code sharing becomes possible 4.Code re-usability increases 5.Increases program readability ●Python Function Types 1. Built-in functions-> predefined, always available ( len(),type(),input() ) 2. Function defined in modules-> predefined in particular module, need to import modules. ( ceil() in math, randint() from random) 3. User defined functions-> defined by programmer.
  • 3. Structure of User Defined Functions Function Header # name of function and its parameters Parameters # variables that are listed within the parentheses of function header Function Body # block of statements indented. Indentation # All statements within same block have same indentation. (usually 4 spaces in the beginning of statement) Non-void Function Void Function 1. def sumofmultiples(n): OR def sumofmultiples(n): s=n*1 + n*2 + n*3 s=n*1 + n*2 + n*3 return s
  • 4. Creating & Calling a Function (user defined) argument:- values being passed are actual arguments (appears in function call) Parameters:- values being received as parameters are formal (appears in function header) A function is defined using the def keyword in python.E.g. program is given below. 1. def my_own_function(d): #Function header 2. print("Hello from a function") #Function Body return d # Function may/maynot have return statement 3. print("hello before calling a function") #main function/ high level 4. r=my_own_function(4) #function call 5. print("hello after calling a function") Flow of execution of program:
  • 5. 1. #Python Program to add two number through function 2. def add2number2(x, y): # here x, y are parameters 3. r=x+y 4. return r 5. 6. # take input from the user 7. num1 = int(input("Enter first number: ")) 8. num2 = int(input("Enter second number: ")) 9. Result=add2numbers(num1, num2) # here num1, num2 are Arguments 10. print("The sum. of", num1,"and", num2,"is",Result) 1. # Python Program to find the factorial of a given number 2. def factorial(n): # parameters= 3. fact = 1 # local variable=fact 4. for i in range(1,n+1): 5. fact = fact * i 6. return fact 7. print ("The factorial of 5 is : ",end="") 8. print (factorial(5)) #arguments=
  • 6.
  • 7.
  • 8.
  • 9. Python Supports three types of formal parameters 1. Positional parameters (Required parameters) 2. Default parameters appears in Function Header 3. Arbitrary parameters/ Variable length parameters 4. Named parameters (Keyword parameters) appears in Function Call 1. def check(a,b,c): 2. s=a+b+c 3. print(s)
  • 10. Default Parameter (Function header) def Check (a=3,b=7,c=100) : s=a+b+c print(s) x,y,z=10,20,30 Check(x,y,z) Check(x,y) Check(x) Check() Named Parameter (Function call) def si(prin=2000,time,rate=0.06): return prin*time*rate Si(9000,5) Si(prin=9000,time=7,rate=0.04) Si(rate=9.0,prin=1000,time=6.1) Si(4000,prin=3000,time=8)
  • 11. Arbitrary arguments / Variable-length Arguments Sometimes you may need more arguments to process function then you mentioned in the definition(when you are passing . If we don’t know in advance about the arguments needed in function, we can use variable-length arguments also called arbitrary arguments. For this an asterisk (*) is placed before a parameter in function definition which can hold non-keyword variable-length arguments and a double asterisk (**) is placed before a parameter in function which can hold keyword variable-length arguments. If we use one asterisk (*) like *var, then all the positional arguments from that point till the end are collected as a tuple called ‘var’ and if we use two asterisks (**) before a variable like **var, then all the positional arguments from that point till the end are collected as a dictionary called ‘var’. def greet(*args): # This function greets all the person in the names tuple. # names is a tuple with arguments for n in args: print("Hello", n) #Calling the function greet("Monica", "Luke", "Steve", "John") Output Hello Monica Hello Luke Hello Steve Hello John def display(*args, **kwargs): """This function display all persons in names tuple. and all keyword arguments as dictionary""" for items in args: print (items) for items in kwargs.items(): print (items) #Calling the function display(‘John','Mary','Nina',Mohan='LA',Seema='NY', Reena='DC‘)
  • 12. Variable’s Scope in function There are three types of variables with the view of scope. 1. Local variable – accessible only inside the functional block where it is declared. 2. Global variable – variable which is accessible among whole program using global keyword. 3. Non local variable – accessible in nesting of functions, using nonlocal keyword. Used in nested functions.
  • 13. Global-Local Environment Global Environment For main() S -> “I love World” Local Environment For fun() S -> “I Love India”
  • 14. Non Local Variable Program 1.def myfunc1(): 2. x = "John" 3. def myfunc2(): 4. global x 5. x = "hello" 6. myfunc2() 7. return x 8.X=“SEEMA” 9.print(myfunc1()) 1.def myfunc1(): 2. x = "John" 3. def myfunc2(): 4. nonlocal x 5. x = "hello" 6. myfunc2() 7. return x 8. 9.print(myfunc1()) Global Environment For main() X->SEEMA Local Environment For myfunc1() X -> “Hello” LOCAL ENV FOR MYFUNC2() x-=“hello”
  • 16. Possible combinations of Returning values from functions 1. non-void functions without arguments 2. non-void functions with some arguments 3. void functions without arguments 4. void functions with some arguments Returning multiple values from funtion 1. def squared(x,y,z) : return x*x, y*y, z*z t=squared(1,2,3) # t is tuple a,b,c=t print(t) 2. def squared(x,y,z) : return x*x, y*y, z*z a,b,c=squared(1,2,3) # unpack received tuple in a,b,c t= (a,b,c) print(t) 1 4 9
  • 17. Write Flow of Execution of program (trace the program). Draw the entire environment, for all variables at the time line 10 is being executed. Predict the output of the program 1. def calcSum(a,b,c): 2. s=a+b+c 3. return s 4. def average( x,y,z): 5. sm=calcSum(x,y,z) 6. return sm / 3 7. n1=int(input(“Number 1:”)) 8. n2=int(input(“Number 2:”)) 9. n3=int(input(“Number 3:”)) 10.print(“Average of these number is”, average(n1,n2,n3)) Flow of execution of program: 1-4-7-8-9-10-4-5-1-2-3-5-6-10 Global Environment n1 -> 11 n2 -> 22 n3 -> 33 22.0 Local Environment For average() X -> 11 Y -> 22 Z -> 33 Sm -> 66 66/3 -> 22.0 Local Environment for calcSum() A -> 11 B -> 22 C-> 33 S -> 66 Lifetime of Variable Local Variable Global Variable It is a variable which is declared within a function or within a block. It is a variable which is declared outside all the functions. It is accessible only within a function/block in which it is declared. It is accessible throughout the program.
  • 18.
  • 19. Passing Immutable Type value to a Function 1. def func1( x): 2. print(“Inside functions my value is :”,x) 3. x=x ** 2 4. print(“Now my value is : “, x) 5. n=3 6. print(“Calling func1() by passing ‘n’ with value :”, n) 7. func1(n) 8. print(“Back from func1(). Now value of ‘n’ is :, n ) # Draw environments and predict the outputs Conclusion- Changes in immutable type are not reflected in the caller function at all. Output- Calling func1() by passing ‘n’ with value :3 Inside functions my value is :3 Now my value is : 9
  • 20. Conclusion- Changes in mutable types are reflected in caller function if its name is not assigned a different variable or datatype 1. def func1(Rlist): 2. print(“Inside function”) 3. print(“Received List: “, Rlist) 4. Rlist[0] += 5 5. print( “List within called function after change: “,Rlist) 6. Slist=[25] 7. print(“List before function call:”,Slist) 8. func1(Slist) 9. print(“List after function call :”, Slist) Rlist Rlist[0] Rlist Rlist[0] Slist Slist[0] 25 25 +5
  • 21. Passing Mutable Type value to a function ( making changes in place) 1. def func1(Rlist) : 2. print(“Inside Function”) 3. print(“Received List :”,Rlist) 4. Rlist.append(100) 5. Rlist.extend ( [ 11,13,17] ) 6. print(“List after adding some elements:”, Rlist) 7. Rlist.remove(13) 8. print(“List after removing one element:”, Rlist) 9. Slist=[25] 10.print(“List before function call : “,Slist) 11.func1(Slist) 12.print(“List after function call : “,Slist) Rlist / Rlist[0] OR Slist/ Slist[0] Rlist Rlist Rlist Slist / Slist[0] Conclusion- Changes in mutable types are reflected in caller function if it is not assigned a different variable or datatype 25 100 11 13 17 25 100 25 100 11 17
  • 22. Passing Mutable Type value to a function ( making changes in place) 1. def func1(Rlist) : 2. print(“Inside Function”) 3. print(“Received List :”,Rlist) 4. Newlist=[1,2,3] 5. Rlist=Newlist 6. Rlist.append(100) 7. Rlist.extend ( [ 11,13,17] ) 8. print(“List after adding some elements:”, Rlist) 9. Rlist.remove(13) 10. print(“List after removing one element:”, Rlist) 11. Slist=[25] 12. print(“List before function call : “,Slist) 13. func1(Slist) 14. print(“List after function call : “,Slist) Rlist / Rlist[0] Newlist =[1,2,3] Rlist =Newlist Rlist .append(100) Rlist.extend([11,13,17]) Rlist Rlist.remove(13) Slist / Slist[0] Conclusion- Changes in mutable types are not reflected in caller function if it is assigned a different variable or datatype within function definition 1 2 3 1 2 3 1 2 3 100 1 2 3 100 11 13 17 1 2 3 100 11 17
  • 23. Resolving scope of a Name (LEGB rule) The LEGB rule is a kind of name lookup procedure, which determines the order in which Python looks up names. Python scopes are implemented as dictionaries that map names to objects. These dictionaries are commonly called namespaces. These are the concrete mechanisms that Python uses to store names. They’re stored in a special attribute called __dict__. (import math and show how to check variables in a module like math.__dict__) L – Local Environment / Namespace- inside function E – Enclosing Environment / Namespace -inside nested functions nonlocal scope G - Global Environment / Namespace- inside main/module scope B - Built-in Environment / Namespace - from anywhere in program (keywords, built in functions and attributes) Otherwise Python would report error. B G E L
  • 24. Lambda Function Python allows us to not declare the function in the standard manner, i.e., by using the def keyword. Rather, the anonymous functions are declared by using lambda keyword. However, Lambda functions can accept any number of arguments, but they can return only one value in the form of expression. Syntax:- lambda arguments : expression Example 1. x = lambda a:a+10 # a is an argument and a+10 is an expression which got evaluated and returned. print("sum = ",x(20)) 2. x = lambda a,b:a+b # a and b are the arguments and a+b is the expression which gets evaluated and returned. print("sum = ",x(20,10)) 3. #the function table(n) prints the table of n def table(n): return lambda a:a*n; # a will contain the iteration variable i and a multiple of n is returned at each function call n = int(input("Enter the number?")) b = table(n) # the entered number is passed into the function table. b will contain a lambda function which # is called again and again with the iteration variable i for i in range(1,11): print(n,"X",i,"=",b(i)) #the lambda function b is called with the iteration variable i,