Document

advertisement
COMPSCI 101
Principles of Programming
Lecture 9 – Divide a problem into different tasks and
define functions which perform each task, trace the
execution of a small program which contains simple
functions
CompSci 101 - Principles of Programming
2
Learning outcomes
 At the end of this lecture, students should be able to:
 break a program into small tasks which can be implemented using functions
 know how to trace code which involves functions
CompSci 101 - Principles of Programming
3
Recap
 From lecture 8




write functions which perform a task
understand that a function can call another function
understand the scope of variable
always use excellent function names and variable names to ensure that the purpose of
the function is clear
Original price $234
5% Discount: $11.7
def get_discount(amount, rate):
Price $222.3
discount = amount * rate / 100
Original price $657
return round(discount, 2)
15% Discount: $98.55
def get_discount_message(discount, rate):
Price $558.45
rate_message = str(rate) + "%"
message = rate_message + " Discount: $" + str(discount)
return message
def print_docket(cost, discount_rate):
#Code not shown here
print_docket(234, 5)
print_docket(657, 15)
CompSci 101 - Principles of Programming
4
Wait for the user to press Enter (return)
 Sometimes we want the user to press Enter when they are ready:
Think of a number (press enter to continue):
Add 5 to the number (press enter to continue):
Times the number by 4 (press enter to continue):
Subtract 8 (press enter to continue):
Times the number by 2 (press enter to continue):
Divide the number by 8 (press enter to continue):
Subtract your original number (press enter to continue):
Any number such as 408
Add 5: 413
Times 4: 1652
Subtract 8: 1644
Times by 2: 3288
Divide by 8: 411
Subtract original number:
3
================================
The number you now have is 3
================================
CompSci 101 - Principles of Programming
5
Wait for the user to press Enter (return)
 Code for the previous slide.
def prompt_continue(prompt):
…
def display_details():
number = random.randrange(0, 500)
…
display_final_number(number)
def display_final_number(number):
…
prompt_continue("Think of a number (press enter to continue)")
prompt_continue("Add 5 to the number (press enter to continue)")
prompt_continue("Times the number by 4 (press enter to continue)")
prompt_continue("Subtract 8 (press enter to continue)")
prompt_continue("Times the number by 2 (press enter to continue)")
prompt_continue("Divide the number by 8 (press enter to continue)")
prompt_continue("Subtract your original number (press enter to
display_details()
continue)")
CompSci 101 - Principles of Programming
6
Madlibs
 A madlib is the name for a simple game. The idea is to take a
sentence and remove some words. You then ask someone to
enter some words which fit the same general category as the
removed words and see what the new sentence is created:
[Mary] had a little [lamb], its fleece was [white] as [snow].
Everywhere that [Mary] went, the [lamb] was sure to [go].
[NAME] had a little [ANIMAL], its fleece was [COLOUR] as
[PLURAL_NOUN]
Everywhere that [NAME] went, the [ANIMAL] was sure to [ACTION]
 Think about the functions needed to write this program (2 functions)
and write the main code for the program.
CompSci 101 - Principles of Programming
7
Madlibs
 From the previous slide.
#write the main code below
CompSci 101 - Principles of Programming
8
Format of CompSci 101 programs from here on
1
2
3
def function1(…):
print("Executing function1()")
….
4
5
6
def function2(…):
print("Executing function2()")
….
7
…
8 def main():
9
function1(…)
10
print("Executing main()")
11
function2(…)
12 main()
CompSci 101 - Principles of Programming
Format of CompSci 101 programs - example
1
2
def to_minutes(hours, minutes):
return hours * 60 + minutes
3
4
5
def display_results(hrs1, hrs2, min1, min2, hrs_diff, mins_diff):
print(hrs1, ":", min1, " to ", hrs2, ":", min2, " is:", sep="")
print(" ", hrs_diff, " hours and ", mins_diff, " minutes.", sep="")
6 def main():
7
time1_hour = 5
8
time1_minutes = 23
9
time2_hour = 23
10
time2_minutes = 14
11
12
time1_mins = to_minutes(time1_hour, time1_minutes)
time2_mins = to_minutes(time2_hour, time2_minutes)
13
diff_mins = time2_mins - time1_mins
14
15
16
diff_hrs = diff_mins // 60
diff_mins = diff_mins % 60
display_results(time1_hour, time2_hour, time1_minutes,
time2_minutes, diff_hrs, diff_mins)
17 main()
9
CompSci 101 - Principles of Programming
10
Code trace – the program stack
1
def test2(age):
2
age = age + 10
3
print("3.", age)
4
def test1(years):
5
print("4.", years)
6
years = 20
7
def main():
8
years = 5
9
test1(years)
10
print("1.", years)
11
test2(years)
12
print("2.", years)
13 main()
The program starts executing on
the first unindented line of code
(line 13).
Every time a function is called
(lines 13, 9 and 11), a section of
space in the computer memory
is set aside for the parameters
and the local variables of the
called function.
When the function finishes
executing, the space set aside
for the function execution is
freed (released).
This code tracing technique will be shown in lectures.
CompSci 101 - Principles of Programming
11
Code trace – the program stack
1
def test2(age):
2
age = age + 10
3
print("3.", age)
4
def test1(years):
5
print("4.", years)
6
years = 20
7
test2() function
age 5 15
def main():
8
years = 5
9
test1(years)
10
print("1.", years)
11
test2(years)
12
print("2.", years)
13 main()
test1() function
years 5 20
4.
1.
3.
2.
5
5
15
5
main() function
years 5
CompSci 101 - Principles of Programming
1
def method1():
2
print("A")
3
method2(3)
4
print("B")
5
def method2(num):
6
print("C")
7
method4(num - 1, num - 2)
8
print("D")
9
10
Do a code trace on the program
and show the output.
Excercise
def method3(number):
print("E", number)
11 def method4(num1, num2):
print("F")
12
13
method3(num1 + num2)
14 def main():
print("G")
15
16
method1()
17 main()
12
main() function
Code trace example
CompSci 101 - Principles of Programming
Part of the code trace for this
program is shown on the next
slide. The rest of the code trace
will be shown in lectures.
1
2
3
def get_part(digits, start, end):
num = int(digits[start: end])
return num
4
5
6
7
8
def number_fiddle(digit_str, number_of_digits):
half_way = number_of_digits // 2
part1 = get_part(digit_str, 0, half_way)
part2 = get_part(digit_str, half_way,
number_of_digits)
return part1 + part2
9
def display_results(num1, num2):
10
print(num1, ", ", num2, sep = "")
11
def main():
12
num = 123
13
fiddled = number_fiddle(str(num), len(str(num)))
14
display_results(num - 5, fiddled)
15
main()
13
CompSci 101 - Principles of Programming
display_results() function
num1
num2
get_part() function
digits
start
end
num
get_part() function
digits
start
end
num
number_fiddle() function
digit_str
number_of_digits
half_way
part1
part2
main() function
123
num
fiddled_number
14
Code Trace of the program
on the previous slide
This code trace example will be
finished in lectures.
CompSci 101 - Principles of Programming
Complete the code trace of the program and
show the output.
1
def first(a):
2
b = 3
3
print("1",
4
return second(a * b) + b
5
a)
6
print("2", a)
7
return a // 2
8
def main():
()
function
first() function
9
a = 3
10
b = first(a)
11
print("3",
12
b = second(b)
13
print("4",
14 main()
Exercise
() function
def second(a):
b)
b)
main() function
a3
b
15
CompSci 101 - Principles of Programming
16
Summary
 Problems can be broken down into small tasks which can be
implemented using functions
 A code tracing technique is used to show the execution of a program
Download