This note is from 1 month ago. You're viewing content from a previous lesson.
B2.3.4 Construct functions and modularization.
--> Time: 45 minutes. Work in pairs, one laptop per pair. <--
STAGE 1 - READ (10 min)
Open the FAQ entry "B2.3.4 Construct functions and modularization"
on faq.computersciencewiki.org. Read sections 1 and 3 only
(Functions, and The Principle of Scope). Skip the Java examples.
Copy this into your notebook and fill in the blanks from the reading:
1. A function is a named block of code that performs a ______ task.
2. The inputs to a function are called ______.
3. The word for sending a value back out of a function is ______.
4. A variable created inside a function is ______ to that function,
which means code outside cannot see it.
STAGE 2 - PREDICT (10 min)
Laptops CLOSED. Write down what each one prints. Then open your
laptop and run them to check.
A) def double(number):
return number * 2
print(double(5))
B) def shout(word):
print(word.upper())
result = shout("hi")
print(result)
C) def add(a, b):
return a + b
print(add(2, 3) + add(10, 1))
D) name = "Sam"
def show():
print(name)
show()
STAGE 3 - BUILD (20 min)
Make a new file called my_functions.py. Write these four functions.
Each one is one or two lines. Run the file after EACH function
so you catch mistakes early.
1. greet(name)
Takes a name. Returns "Hello Ana!" when given "Ana".
2. double(number)
Takes a number. Returns that number times 2.
3. area(width, height)
Takes two numbers. Returns width times height.
4. is_long(word)
Takes a word. Returns True if it is longer than 5 letters,
otherwise False.
Now add these lines at the bottom and run the file.
You should see exactly the output shown on the right:
print(greet("Ana")) -> Hello Ana!
print(double(7)) -> 14
print(area(3, 4)) -> 12
print(is_long("banana")) -> True
print(is_long("cat")) -> False
Two rules:
- Every function must use return, not print.
- Do not write any function longer than two lines.
STUCK? Here is the shape every one of them follows:
def name_of_function(input):
return something
STAGE 4 - EXIT TICKET (5 min)
Answer on paper and hand in:
1. You wrote double(number). Show the line of code you would write
to double the number 30 and store the answer in a variable
called big.
2. Why is it better to write double() once and call it five times,
instead of writing number * 2 in five different places?
3. Look at your area() function. Why does it need two parameters
when greet() only needs one?
IF YOU FINISH EARLY
Add a fifth function called triple(number) that returns the number
times 3. Then write one line that uses double() and triple()
together on the same number and prints the total.