SlideShare uma empresa Scribd logo
1 de 55
1ARULKUMAR V AP/CSE SECE
2
Find the sum of integers from 1 to 10, from 20 to 37, and
from 35 to 49, respectively.
ARULKUMAR V AP/CSE SECE
3
sum = 0
for i in range(1, 10):
sum += i
print("Sum from 1 to 10 is", sum)
sum = 0
for i in range(20, 37):
sum += i
print("Sum from 20 to 37 is", sum)
sum = 0
for i in range(35, 49):
sum += i
print("Sum from 35 to 49 is", sum)
ARULKUMAR V AP/CSE SECE
4
sum = 0
for i in range(1, 10):
sum += i
print("Sum from 1 to 10 is", sum)
sum = 0
for i in range(20, 37):
sum += i
print("Sum from 20 to 37 is", sum)
sum = 0
for i in range(35, 49):
sum += i
print("Sum from 35 to 49 is", sum)
ARULKUMAR V AP/CSE SECE
5
def sum(i1, i2):
result = 0
for i in range(i1, i2):
result += i
return result
def main():
print("Sum from 1 to 10 is", sum(1, 10))
print("Sum from 20 to 37 is", sum(20, 37))
print("Sum from 35 to 49 is", sum(35, 49))
main() # Call the main function
ARULKUMAR V AP/CSE SECE
 To define functions (§6.2).
 To invoke value-returning functions (§6.3).
 To invoke functions that does not return a value (§6.4).
 To pass arguments by values (§6.5).
 To pass arguments by values (§6.6).
 To develop reusable code that is modular, easy to read,
easy to debug, and easy to maintain (§6.7).
 To create modules for reusing functions (§§6.7-6.8).
 To determine the scope of variables (§6.9).
 To define functions with default arguments (§6.10).
 To return multiple values from a function (§6.11).
 To apply the concept of function abstraction in
software development (§6.12).
 To design and implement functions using stepwise
refinement (§6.13).
 To simplify drawing programs using functions (§6.14).
6ARULKUMAR V AP/CSE SECE
7
A function is a collection of statements that are
grouped together to perform an operation.
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
function name formal parameters
return value
function
body
function
header
Define a function Invoke a function
z = max(x, y)
actual parameters
(arguments)
ARULKUMAR V AP/CSE SECE
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
function name formal parameters
return value
function
body
function
header
Define a function Invoke a function
z = max(x, y)
actual parameters
(arguments)
8
A function contains a header and body. The header begins with the
def keyword, followed by function’s name and parameters,
followed by a colon.
ARULKUMAR V AP/CSE SECE
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
function name formal parameters
return value
function
body
function
header
Define a function Invoke a function
z = max(x, y)
actual parameters
(arguments)
9
The variables defined in the function header are known as
formal parameters.
ARULKUMAR V AP/CSE SECE
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
function name formal parameters
return value
function
body
function
header
Define a function Invoke a function
z = max(x, y)
actual parameters
(arguments)
10
When a function is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
ARULKUMAR V AP/CSE SECE
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
function name formal parameters
return value
function
body
function
header
Define a function Invoke a function
z = max(x, y)
actual parameters
(arguments)
11
A function may return a value using the return keyword.
ARULKUMAR V AP/CSE SECE
12
Testing the max function
This program demonstrates calling a function
max to return the largest of the int values
TestMax Run
ARULKUMAR V AP/CSE SECE
13
animation
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
ARULKUMAR V AP/CSE SECE
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
14
animation
Invoke the main function
ARULKUMAR V AP/CSE SECE
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
15
animation
i is now 5
ARULKUMAR V AP/CSE SECE
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
16
animation
j is now 2
ARULKUMAR V AP/CSE SECE
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
17
animation
invoke max(i, j)
ARULKUMAR V AP/CSE SECE
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
18
animation
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2
ARULKUMAR V AP/CSE SECE
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
19
animation
(num1 > num2) is true
since num1 is 5 and num2
is 2
ARULKUMAR V AP/CSE SECE
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
20
animation
result is now 5
ARULKUMAR V AP/CSE SECE
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
21
animation
return result, which is 5
ARULKUMAR V AP/CSE SECE
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
22
animation
return max(i, j) and assign
the return value to k
ARULKUMAR V AP/CSE SECE
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
23
animation
Execute the print
statement
ARULKUMAR V AP/CSE SECE
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
24
animation
Return to the caller
ARULKUMAR V AP/CSE SECE
25
(a) The main function
is invoked.
Space required for
the main function
j: 2
i: 5
(b) The max
function is invoked.
(c) The max function
is being executed.
Space required for
the main function
j:
i:
Space required for
the max function
num2:
num1:
int object
5
int object
2
This is a heap for
storing objects
stack stack
int object
5
int object
2
This is a heap for
storing objects
Space required for
the main function
j:
i:
Space required for
the max function
result:
num2:
num1:
stack
ARULKUMAR V AP/CSE SECE
26
Space required for
the main function
k:
j: 2
i: 5
(e) The main
function is finished.
int object
5
int object
2
This is a heap for
storing objects
stack stack
(d) The max function is
finished and the return
value is sent to k.
Stack is
now empty
ARULKUMAR V AP/CSE SECE
27
This type of function does not return a value. The
function performs some actions.
ReturnGradeFunction Run
PrintGradeFunction Run
ARULKUMAR V AP/CSE SECE
28
A function that does not return a value is known as
a void function in other programming languages
such as Python, C++, and C#. In Python, such
function returns a special None.
def sum(number1, number2):
total = number1 + number2
print(sum(1, 2))
ARULKUMAR V AP/CSE SECE
def nPrintln(message, n):
for i in range(0, n):
print(message)
29
Suppose you invoke the function using
nPrintln(“Welcome to Python”, 5)
What is the output?
Suppose you invoke the function using
nPrintln(“Computer Science”, 15)
What is the output?
What is wrong
nPrintln(4, “Computer Science”)
ARULKUMAR V AP/CSE SECE
def nPrintln(message, n):
for i in range(0, n):
print(message)
30
What is wrong
nPrintln(4, “Computer Science”)
Is this OK?
nPrintln(n = 4, message = “Computer Science”)
ARULKUMAR V AP/CSE SECE
31
In Python, all data are objects. A variable for an object is actually a
reference to the object. When you invoke a function with a
parameter, the reference value of the argument is passed to the
parameter. This is referred to as pass-by-value. For simplicity, we
say that the value of an argument is passed to a parameter when
invoking a function. Precisely, the value is actually a reference value
to the object.
Increment Run
If the argument is a number or a string, the argument is not affected,
regardless of the changes made to the parameter inside the function.
ARULKUMAR V AP/CSE SECE
Functions can be used to reduce redundant coding
and enable code reuse. Functions can also be used
to modularize code and improve the quality of the
program.
32
GCDFunction
Run
PrimeNumberFunction
Run
TestGCDFunction
ARULKUMAR V AP/CSE SECE
33
Write a function that converts a decimal integer
to a hexadecimal.
Decimal2HexConversion RunDecimal2HexConversion Run
ARULKUMAR V AP/CSE SECE
Scope: the part of the program
where the variable can be
referenced.
34
A variable created inside a function is referred to as a
local variable. Local variables can only be
accessed inside a function. The scope of a local
variable starts from its creation and continues to
the end of the function that contains the variable.
In Python, you can also use global variables. They
are created outside all functions and are accessible
to all functions in their scope.
ARULKUMAR V AP/CSE SECE
globalVar = 1
def f1():
localVar = 2
print(globalVar)
print(localVar)
f1()
print(globalVar)
print(localVar) # Out of scope. This gives an error
35ARULKUMAR V AP/CSE SECE
x = 1
def f1():
x = 2
print(x) # Displays 2
f1()
print(x) # Displays 1
36ARULKUMAR V AP/CSE SECE
x = eval(input("Enter a number: "))
if (x > 0):
y = 4
print(y) # This gives an error if y is not created
37ARULKUMAR V AP/CSE SECE
sum = 0
for i in range(0, 5):
sum += i
print(i)
38ARULKUMAR V AP/CSE SECE
x = 1
def increase():
global x
x = x + 1
print(x) # Displays 2
increase()
print(x) # Displays 2
39ARULKUMAR V AP/CSE SECE
Python allows you to define functions with
default argument values. The default values are
passed to the parameters when a function is
invoked without the arguments.
40
DefaultArgumentDemo Run
ARULKUMAR V AP/CSE SECE
Python allows a function to return multiple
values. Listing 5.9 defines a function that takes
two numbers and returns them in non-
descending order.
41
MultipleReturnValueDemo
Run
ARULKUMAR V AP/CSE SECE
42
TestRandomCharacter
Run
RandomCharacter
ARULKUMAR V AP/CSE SECE
You can think of the function body as a black box
that contains the detailed implementation for the
function.
43
Function Header
Function Body
Black Box
Optional arguments
for input
Optional return
value
ARULKUMAR V AP/CSE SECE
44
• Write a function once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
ARULKUMAR V AP/CSE SECE
The concept of function abstraction can be
applied to the process of developing programs.
When writing a large program, you can use the
“divide and conquer” strategy, also known as
stepwise refinement, to decompose it into
subproblems. The subproblems can be further
decomposed into smaller, more manageable
problems.
45ARULKUMAR V AP/CSE SECE
Let us use the PrintCalendar example to
demonstrate the stepwise refinement
approach.
46
PrintCalendar Run
ARULKUMAR V AP/CSE SECE
47
printCalendar
(main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
ARULKUMAR V AP/CSE SECE
48
printCalendar
(main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
ARULKUMAR V AP/CSE SECE
49
printCalendar
(main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
ARULKUMAR V AP/CSE SECE
50
printCalendar
(main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
ARULKUMAR V AP/CSE SECE
51
printCalendar
(main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
ARULKUMAR V AP/CSE SECE
52
printCalendar
(main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
ARULKUMAR V AP/CSE SECE
53
A Skeleton for printCalendar
Top-down approach is to implement one function in the
structure chart at a time from the top to the bottom. Stubs
can be used for the functions waiting to be implemented.
A stub is a simple but incomplete version of a function.
The use of stubs enables you to test invoking the function
from a caller. Implement the main function first and then
use a stub for the printMonth function. For example, let
printMonth display the year and the month in the stub.
Thus, your program may begin like this:
ARULKUMAR V AP/CSE SECE
54
Bottom-up approach is to implement one function in the
structure chart at a time from the bottom to the top. For
each function implemented, write a test program to test it.
Both top-down and bottom-up functions are fine. Both
approaches implement the functions incrementally and
help to isolate programming errors and makes debugging
easy. Sometimes, they can be used together.
ARULKUMAR V AP/CSE SECE
55
UseCustomTurtleFunctions
def drawLine(x1, y1, x2, y2):
def writeString(s, x, y):
def drawPoint(x, y):
def drawCircle(x = 0, y = 0, radius = 10):
def drawRectangle(x = 0, y = 0, width = 10, height = 10):
UsefulTurtleFunctions
Run
ARULKUMAR V AP/CSE SECE

Mais conteúdo relacionado

Mais procurados

Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in Python
Colin Su
 
Hello, i have an assignment ot change the java implementation of Bellman Ford...
Hello, i have an assignment ot change the java implementation of Bellman Ford...Hello, i have an assignment ot change the java implementation of Bellman Ford...
Hello, i have an assignment ot change the java implementation of Bellman Ford...
hwbloom149
 

Mais procurados (20)

Qno 1 (a)
Qno 1 (a)Qno 1 (a)
Qno 1 (a)
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
 
Bayesian workflow with PyMC3 and ArviZ
Bayesian workflow with PyMC3 and ArviZBayesian workflow with PyMC3 and ArviZ
Bayesian workflow with PyMC3 and ArviZ
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with go
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
 
Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in Python
 
Java Programming Workshop
Java Programming WorkshopJava Programming Workshop
Java Programming Workshop
 
statistics assignment help
statistics assignment helpstatistics assignment help
statistics assignment help
 
Hello, i have an assignment ot change the java implementation of Bellman Ford...
Hello, i have an assignment ot change the java implementation of Bellman Ford...Hello, i have an assignment ot change the java implementation of Bellman Ford...
Hello, i have an assignment ot change the java implementation of Bellman Ford...
 
logistic regression with python and R
logistic regression with python and Rlogistic regression with python and R
logistic regression with python and R
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
 
XIX PUG-PE - Pygame game development
XIX PUG-PE - Pygame game developmentXIX PUG-PE - Pygame game development
XIX PUG-PE - Pygame game development
 
Introduction to Gura Programming Language
Introduction to Gura Programming LanguageIntroduction to Gura Programming Language
Introduction to Gura Programming Language
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
 
6. function
6. function6. function
6. function
 
Image processing lab work
Image processing lab workImage processing lab work
Image processing lab work
 
Phil Bartie QGIS PLPython
Phil Bartie QGIS PLPythonPhil Bartie QGIS PLPython
Phil Bartie QGIS PLPython
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 

Semelhante a 4. functions

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
 
Python summer course play with python (lab1)
Python summer course  play with python  (lab1)Python summer course  play with python  (lab1)
Python summer course play with python (lab1)
iloveallahsomuch
 
Python summer course play with python (lab1)
Python summer course  play with python  (lab1)Python summer course  play with python  (lab1)
Python summer course play with python (lab1)
iloveallahsomuch
 

Semelhante a 4. functions (20)

Functions
FunctionsFunctions
Functions
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Python 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxPython 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptx
 
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...
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP
 
III MCS python lab (1).pdf
III MCS python lab (1).pdfIII MCS python lab (1).pdf
III MCS python lab (1).pdf
 
functions
functionsfunctions
functions
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Functions Practice Sheet.docx
Functions Practice Sheet.docxFunctions Practice Sheet.docx
Functions Practice Sheet.docx
 
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
 
Python summer course play with python (lab1)
Python summer course  play with python  (lab1)Python summer course  play with python  (lab1)
Python summer course play with python (lab1)
 
Python summer course play with python (lab1)
Python summer course  play with python  (lab1)Python summer course  play with python  (lab1)
Python summer course play with python (lab1)
 
Functions in c
Functions in cFunctions in c
Functions in c
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
ملخص البرمجة المرئية - الوحدة الخامسة
ملخص البرمجة المرئية - الوحدة الخامسةملخص البرمجة المرئية - الوحدة الخامسة
ملخص البرمجة المرئية - الوحدة الخامسة
 

Mais de PhD Research Scholar

Mais de PhD Research Scholar (20)

Ajax
AjaxAjax
Ajax
 
Quiz servlet
Quiz servletQuiz servlet
Quiz servlet
 
Quiz
QuizQuiz
Quiz
 
servlet db connectivity
servlet db connectivityservlet db connectivity
servlet db connectivity
 
2.java script dom
2.java script  dom2.java script  dom
2.java script dom
 
1.java script
1.java script1.java script
1.java script
 
Quiz javascript
Quiz javascriptQuiz javascript
Quiz javascript
 
Thread&multithread
Thread&multithreadThread&multithread
Thread&multithread
 
String
StringString
String
 
Streams&io
Streams&ioStreams&io
Streams&io
 
Packages
PackagesPackages
Packages
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Inheritance
InheritanceInheritance
Inheritance
 
Exception handling
Exception handlingException handling
Exception handling
 
Applets
AppletsApplets
Applets
 
Abstract class
Abstract classAbstract class
Abstract class
 
7. tuples, set & dictionary
7. tuples, set & dictionary7. tuples, set & dictionary
7. tuples, set & dictionary
 
6. list
6. list6. list
6. list
 
5. string
5. string5. string
5. string
 

Último

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 

Último (20)

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 

4. functions

  • 2. 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively. ARULKUMAR V AP/CSE SECE
  • 3. 3 sum = 0 for i in range(1, 10): sum += i print("Sum from 1 to 10 is", sum) sum = 0 for i in range(20, 37): sum += i print("Sum from 20 to 37 is", sum) sum = 0 for i in range(35, 49): sum += i print("Sum from 35 to 49 is", sum) ARULKUMAR V AP/CSE SECE
  • 4. 4 sum = 0 for i in range(1, 10): sum += i print("Sum from 1 to 10 is", sum) sum = 0 for i in range(20, 37): sum += i print("Sum from 20 to 37 is", sum) sum = 0 for i in range(35, 49): sum += i print("Sum from 35 to 49 is", sum) ARULKUMAR V AP/CSE SECE
  • 5. 5 def sum(i1, i2): result = 0 for i in range(i1, i2): result += i return result def main(): print("Sum from 1 to 10 is", sum(1, 10)) print("Sum from 20 to 37 is", sum(20, 37)) print("Sum from 35 to 49 is", sum(35, 49)) main() # Call the main function ARULKUMAR V AP/CSE SECE
  • 6.  To define functions (§6.2).  To invoke value-returning functions (§6.3).  To invoke functions that does not return a value (§6.4).  To pass arguments by values (§6.5).  To pass arguments by values (§6.6).  To develop reusable code that is modular, easy to read, easy to debug, and easy to maintain (§6.7).  To create modules for reusing functions (§§6.7-6.8).  To determine the scope of variables (§6.9).  To define functions with default arguments (§6.10).  To return multiple values from a function (§6.11).  To apply the concept of function abstraction in software development (§6.12).  To design and implement functions using stepwise refinement (§6.13).  To simplify drawing programs using functions (§6.14). 6ARULKUMAR V AP/CSE SECE
  • 7. 7 A function is a collection of statements that are grouped together to perform an operation. def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result function name formal parameters return value function body function header Define a function Invoke a function z = max(x, y) actual parameters (arguments) ARULKUMAR V AP/CSE SECE
  • 8. def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result function name formal parameters return value function body function header Define a function Invoke a function z = max(x, y) actual parameters (arguments) 8 A function contains a header and body. The header begins with the def keyword, followed by function’s name and parameters, followed by a colon. ARULKUMAR V AP/CSE SECE
  • 9. def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result function name formal parameters return value function body function header Define a function Invoke a function z = max(x, y) actual parameters (arguments) 9 The variables defined in the function header are known as formal parameters. ARULKUMAR V AP/CSE SECE
  • 10. def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result function name formal parameters return value function body function header Define a function Invoke a function z = max(x, y) actual parameters (arguments) 10 When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. ARULKUMAR V AP/CSE SECE
  • 11. def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result function name formal parameters return value function body function header Define a function Invoke a function z = max(x, y) actual parameters (arguments) 11 A function may return a value using the return keyword. ARULKUMAR V AP/CSE SECE
  • 12. 12 Testing the max function This program demonstrates calling a function max to return the largest of the int values TestMax Run ARULKUMAR V AP/CSE SECE
  • 13. 13 animation def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() ARULKUMAR V AP/CSE SECE
  • 14. def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() 14 animation Invoke the main function ARULKUMAR V AP/CSE SECE
  • 15. def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() 15 animation i is now 5 ARULKUMAR V AP/CSE SECE
  • 16. def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() 16 animation j is now 2 ARULKUMAR V AP/CSE SECE
  • 17. def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() 17 animation invoke max(i, j) ARULKUMAR V AP/CSE SECE
  • 18. def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() 18 animation invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2 ARULKUMAR V AP/CSE SECE
  • 19. def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() 19 animation (num1 > num2) is true since num1 is 5 and num2 is 2 ARULKUMAR V AP/CSE SECE
  • 20. def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() 20 animation result is now 5 ARULKUMAR V AP/CSE SECE
  • 21. def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() 21 animation return result, which is 5 ARULKUMAR V AP/CSE SECE
  • 22. def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() 22 animation return max(i, j) and assign the return value to k ARULKUMAR V AP/CSE SECE
  • 23. def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() 23 animation Execute the print statement ARULKUMAR V AP/CSE SECE
  • 24. def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k) def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result pass int 5 pass int 2 main() 24 animation Return to the caller ARULKUMAR V AP/CSE SECE
  • 25. 25 (a) The main function is invoked. Space required for the main function j: 2 i: 5 (b) The max function is invoked. (c) The max function is being executed. Space required for the main function j: i: Space required for the max function num2: num1: int object 5 int object 2 This is a heap for storing objects stack stack int object 5 int object 2 This is a heap for storing objects Space required for the main function j: i: Space required for the max function result: num2: num1: stack ARULKUMAR V AP/CSE SECE
  • 26. 26 Space required for the main function k: j: 2 i: 5 (e) The main function is finished. int object 5 int object 2 This is a heap for storing objects stack stack (d) The max function is finished and the return value is sent to k. Stack is now empty ARULKUMAR V AP/CSE SECE
  • 27. 27 This type of function does not return a value. The function performs some actions. ReturnGradeFunction Run PrintGradeFunction Run ARULKUMAR V AP/CSE SECE
  • 28. 28 A function that does not return a value is known as a void function in other programming languages such as Python, C++, and C#. In Python, such function returns a special None. def sum(number1, number2): total = number1 + number2 print(sum(1, 2)) ARULKUMAR V AP/CSE SECE
  • 29. def nPrintln(message, n): for i in range(0, n): print(message) 29 Suppose you invoke the function using nPrintln(“Welcome to Python”, 5) What is the output? Suppose you invoke the function using nPrintln(“Computer Science”, 15) What is the output? What is wrong nPrintln(4, “Computer Science”) ARULKUMAR V AP/CSE SECE
  • 30. def nPrintln(message, n): for i in range(0, n): print(message) 30 What is wrong nPrintln(4, “Computer Science”) Is this OK? nPrintln(n = 4, message = “Computer Science”) ARULKUMAR V AP/CSE SECE
  • 31. 31 In Python, all data are objects. A variable for an object is actually a reference to the object. When you invoke a function with a parameter, the reference value of the argument is passed to the parameter. This is referred to as pass-by-value. For simplicity, we say that the value of an argument is passed to a parameter when invoking a function. Precisely, the value is actually a reference value to the object. Increment Run If the argument is a number or a string, the argument is not affected, regardless of the changes made to the parameter inside the function. ARULKUMAR V AP/CSE SECE
  • 32. Functions can be used to reduce redundant coding and enable code reuse. Functions can also be used to modularize code and improve the quality of the program. 32 GCDFunction Run PrimeNumberFunction Run TestGCDFunction ARULKUMAR V AP/CSE SECE
  • 33. 33 Write a function that converts a decimal integer to a hexadecimal. Decimal2HexConversion RunDecimal2HexConversion Run ARULKUMAR V AP/CSE SECE
  • 34. Scope: the part of the program where the variable can be referenced. 34 A variable created inside a function is referred to as a local variable. Local variables can only be accessed inside a function. The scope of a local variable starts from its creation and continues to the end of the function that contains the variable. In Python, you can also use global variables. They are created outside all functions and are accessible to all functions in their scope. ARULKUMAR V AP/CSE SECE
  • 35. globalVar = 1 def f1(): localVar = 2 print(globalVar) print(localVar) f1() print(globalVar) print(localVar) # Out of scope. This gives an error 35ARULKUMAR V AP/CSE SECE
  • 36. x = 1 def f1(): x = 2 print(x) # Displays 2 f1() print(x) # Displays 1 36ARULKUMAR V AP/CSE SECE
  • 37. x = eval(input("Enter a number: ")) if (x > 0): y = 4 print(y) # This gives an error if y is not created 37ARULKUMAR V AP/CSE SECE
  • 38. sum = 0 for i in range(0, 5): sum += i print(i) 38ARULKUMAR V AP/CSE SECE
  • 39. x = 1 def increase(): global x x = x + 1 print(x) # Displays 2 increase() print(x) # Displays 2 39ARULKUMAR V AP/CSE SECE
  • 40. Python allows you to define functions with default argument values. The default values are passed to the parameters when a function is invoked without the arguments. 40 DefaultArgumentDemo Run ARULKUMAR V AP/CSE SECE
  • 41. Python allows a function to return multiple values. Listing 5.9 defines a function that takes two numbers and returns them in non- descending order. 41 MultipleReturnValueDemo Run ARULKUMAR V AP/CSE SECE
  • 43. You can think of the function body as a black box that contains the detailed implementation for the function. 43 Function Header Function Body Black Box Optional arguments for input Optional return value ARULKUMAR V AP/CSE SECE
  • 44. 44 • Write a function once and reuse it anywhere. • Information hiding. Hide the implementation from the user. • Reduce complexity. ARULKUMAR V AP/CSE SECE
  • 45. The concept of function abstraction can be applied to the process of developing programs. When writing a large program, you can use the “divide and conquer” strategy, also known as stepwise refinement, to decompose it into subproblems. The subproblems can be further decomposed into smaller, more manageable problems. 45ARULKUMAR V AP/CSE SECE
  • 46. Let us use the PrintCalendar example to demonstrate the stepwise refinement approach. 46 PrintCalendar Run ARULKUMAR V AP/CSE SECE
  • 53. 53 A Skeleton for printCalendar Top-down approach is to implement one function in the structure chart at a time from the top to the bottom. Stubs can be used for the functions waiting to be implemented. A stub is a simple but incomplete version of a function. The use of stubs enables you to test invoking the function from a caller. Implement the main function first and then use a stub for the printMonth function. For example, let printMonth display the year and the month in the stub. Thus, your program may begin like this: ARULKUMAR V AP/CSE SECE
  • 54. 54 Bottom-up approach is to implement one function in the structure chart at a time from the bottom to the top. For each function implemented, write a test program to test it. Both top-down and bottom-up functions are fine. Both approaches implement the functions incrementally and help to isolate programming errors and makes debugging easy. Sometimes, they can be used together. ARULKUMAR V AP/CSE SECE
  • 55. 55 UseCustomTurtleFunctions def drawLine(x1, y1, x2, y2): def writeString(s, x, y): def drawPoint(x, y): def drawCircle(x = 0, y = 0, radius = 10): def drawRectangle(x = 0, y = 0, width = 10, height = 10): UsefulTurtleFunctions Run ARULKUMAR V AP/CSE SECE