Programming Lecture 6
Programming Lecture 6
Applied Programming
1
Opening Problem
Find the sum of integers from 1 to 10, from 20 to 37, and
from 35 to 49, respectively.
2
Problem
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)
3
Problem
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)
4
Solution
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))
5
Defining Functions
A function is a collection of statements that are
grouped together to perform an operation.
Define a function Invoke a function
function z = max(x, y)
def max(num1, num2):
header
if num1 > num2:
function actual parameters
result = num1 (arguments)
body else:
result = num2
return result
return value
6
Function Header
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.
7
Formal Parameters
The variables defined in the function header are known as
formal parameters.
8
Actual Parameters
When a function is invoked, you pass a value to the parameter.
This value is referred to as actual parameter or argument.
function z = max(x, y)
def max(num1, num2):
header
if num1 > num2:
function actual parameters
result = num1 (arguments)
body else:
result = num2
return result
return value
9
Return Value
A function may return a value using the return keyword.
Define a function Invoke a function
function z = max(x, y)
def max(num1, num2):
header
if num1 > num2:
function actual parameters
result = num1 (arguments)
body else:
result = num2
return result
return value
10
Calling Functions
Testing the max function
This program demonstrates calling a function
max to return the largest of the int values
TestMax
11
Calling Functions, cont.
pass int 5
pass int 2
12
Trace Function Invocation
Invoke the main function
pass int 5
pass int 2
13
Trace Function Invocation
i is now 5
pass int 5
pass int 2
14
animation
pass int 5
pass int 2
15
animation
pass int 5
pass int 2
16
animation
17
animation
18
animation
pass int 5
pass int 2
19
animation
pass int 5
pass int 2
20
animation
21
animation
22
animation
pass int 5
pass int 2
23
Call Stacks
(a) The main function This is a heap for (b) The max This is a heap for (c) The max function
is invoked. storing objects function is invoked. storing objects is being executed.
24
Call Stacks
stack stack
int object
Space required for
2
the main function Stack is
k: now empty
j: 2 int object
i: 5 5
(d) The max function is This is a heap for (e) The main
finished and the return storing objects function is finished.
value is sent to k.
25
Functions With/Without Return
Values
This type of function does not return a value. The
function performs some actions.
PrintGradeFunction
ReturnGradeFunction
26
The None Value
27
Passing Arguments by
Positions
def nPrintln(message, n):
for i in range(0, n):
print(message)
Suppose you invoke the function using
nPrintln(“Welcome to Python”, 5)
What is the output?
What is wrong
nPrintln(4, “Computer Science”)
28
Keyword Arguments
def nPrintln(message, n):
for i in range(0, n):
print(message)
What is wrong
nPrintln(4, “Computer Science”)
Is this OK?
nPrintln(n = 4, message = “Computer Science”)
29
Pass by Value
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
30
Modularizing Code
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.
GCDFunction TestGCDFunction
PrimeNumberFunction
31
Problem: Converting Decimals to
Hexadecimals
Write a function that converts a decimal integer
to a hexadecimal.
Decimal2HexConversion
32
Scope of Variables
Scope: the part of the program where the
variable can be referenced.
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.
33
Example 1
globalVar = 1
def f1():
localVar = 2
print(globalVar)
print(localVar)
f1()
print(globalVar)
print(localVar) # Out of scope. This gives an error
34
Example 2
x = 1
def f1():
x = 2
print(x) # Displays 2
f1()
print(x) # Displays 1
35
Example 3
x = eval(input("Enter a number: "))
if (x > 0):
y=4
print(y) # This gives an error if y is not created
36
Example 4
sum = 0
for i in range(0, 5):
sum += i
print(i)
37
Example 5
x = 1
def increase():
global x
x = x + 1
print(x) # Displays 2
increase()
print(x) # Displays 2
38
Default Arguments
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.
DefaultArgumentDemo
39
Returning Multiple Values
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.
MultipleReturnValueDemo
40
Generating Random
Characters
RandomCharacter
TestRandomCharacter
41
Function Abstraction
You can think of the function body as a black box that
contains the detailed implementation for the function.
Function Header
Black Box
Function Body
42
Benefits of Functions
• Write a function once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
43
Stepwise Refinement
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.
44
PrintCalender Case Study
Let us use the PrintCalendar example to demonstrate the
stepwise refinement approach.
PrintCalendar
45
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
46
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
47
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
48
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
49
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
50
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
51
Implementation: Top-Down
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:
52
Implementation: Bottom-Up
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.
53
Turtle:
Developing Reusable Graphics
Functions
def drawLine(x1, y1, x2, y2): UsefulTurtleFunctions
UseCustomTurtleFunctions
54