Lab 1: Functions, Control
Due by 11:59pm on Tuesday, July 1.
Starter Files
Download lab01.zip.
Required Questions
Review
Important: If the
python3
command doesn't work, please try usingpython
orpy
.
Using no command-line options will run the code in the file you provide and return you to the command line. If your file just contains function definitions, you'll see no output unless there is a syntax error.
python3 lab00.py
-i
: The-i
option runs the code in the file you provide, then opens an interactive session (with a>>>
prompt). You can then evaluate expressions such as calling functions you defined. To exit, typeexit()
. You can also use the keyboard shortcutCtrl-D
on Linux/Mac machines orCtrl-Z Enter
on Windows.If you edit the Python file while running it interactively, you will need to exit and restart the interpreter in order for those changes to take effect.
Here's how we can run
lab00.py
interactively:python3 -i lab00.py
-m doctest
: Runs the doctests in a file, which are the examples in the docstrings of functions.Each test in the file consists of
>>>
followed by some Python code and the expected output.Here's how we can run the doctests in
lab00.py
:python3 -m doctest lab00.py
When our code passes all of the doctests, no output is displayed. Otherwise, information about the tests that failed will be displayed.
To use Ok to test a function, run the following command (replacing FUNCTION
with the name of the function):
python3 ok -q FUNCTION
If your function contains a call to print
that starts with "DEBUG:"
, then this line will be ignored by OK. (Otherwise, including extra print
calls can cause tests to fail because of the additional output displayed.)
print("DEBUG:", x)
There are more features described on the Using OK page. You can quickly generate most ok commands at ok-help.
True Division: / (decimal division) |
Floor Division: // (integer division) |
Modulo: % (remainder) |
---|---|---|
|
|
|
A ZeroDivisionError
occurs when dividing by 0.
One useful technique involving the %
operator is to check
whether a number x
is divisible by another number y
:
x % y == 0
For example, in order to check if x
is an even number: x % 2 == 0
return
statement that provides
the value of the call expression used to call the function.
When Python executes a return
statement, the function call terminates
immediately. If Python reaches the end of the function body without executing
a return
statement, the function returns None
.
In contrast, the print
function is used to display values.
Unlike a return
statement, when Python evaluates a call to print
, the
function does not terminate immediately.
def what_prints():
print('Hello World!')
return 'Exiting this function.'
print('This course is awesome!')
>>> what_prints()
Hello World!
'Exiting this function.'
Notice also that
return
will preserve the quotes.
Getting Started Videos
These videos may provide some helpful direction for tackling the coding problems on this assignment.
To see these videos, you should be logged into your berkeley.edu email.
What Would Python Display? (WWPD)
Q1: Return and Print
Use Ok to test your knowledge with the following "What Would Python Display?" questions:
python3 ok -q return-and-print -u
>>> def welcome():
... print('Go')
... return 'hello'
...
>>> def cal():
... print('Bears')
... return 'world'
...
>>> welcome()
______Go
'hello'
>>> print(welcome(), cal())
______Go
Bears
hello world
Q2: WWPD: What If?
Use Ok to test your knowledge with the following "What Would Python Display?" questions:
python3 ok -q if-statements -u
Hint:
return
) does not cause the function to exit.
>>> def ab(c, d):
... if c > 5:
... print(c)
... elif c > 7:
... print(d)
... print('foo')
>>> ab(10, 20)
______10
foo
>>> def bake(cake, make):
... if cake == 0:
... cake = cake + 1
... print(cake)
... if cake == 1:
... print(make)
... else:
... return cake
... return make
>>> bake(0, 29)
______1
29
29
>>> bake(1, "mashed potatoes")
______mashed potatoes
'mashed potatoes'
Debugging Quiz
Q3: Debugging Quiz
The following is a quick quiz on different debugging techniques that will be helpful for you to use in this class. You can refer to the debugging article to answer the questions.
Use Ok to test your understanding:
python3 ok -q debugging-quiz -u
Write Code
Q4: Falling Factorial
Let's write a function falling
, which is a "falling" factorial
that takes two arguments, n
and k
, and returns the product of k
consecutive numbers, starting from n
and working downwards.
When k
is 0, the function should return 1.
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
"*** YOUR CODE HERE ***"
Use Ok to test your code:
python3 ok -q falling
Q5: Divisible By k
Write a function divisible_by_k
that takes positive integers n
and k
. It prints all positive integers less than or equal to n
that are divisible by k
from smallest to largest. Then, it returns how many numbers were printed.
def divisible_by_k(n, k):
"""
>>> a = divisible_by_k(10, 2) # 2, 4, 6, 8, and 10 are divisible by 2
2
4
6
8
10
>>> a
5
>>> b = divisible_by_k(3, 1) # 1, 2, and 3 are divisible by 1
1
2
3
>>> b
3
>>> c = divisible_by_k(6, 7) # There are no integers up to 6 that are divisible by 7
>>> c
0
"""
"*** YOUR CODE HERE ***"
Use Ok to test your code:
python3 ok -q divisible_by_k
Q6: Double Eights
Write a function that takes in a number and determines if the digits contain two adjacent 8s.
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
"*** YOUR CODE HERE ***"
Use Ok to test your code:
python3 ok -q double_eights
Check Your Score Locally
You can locally check your score on each question of this assignment by running
python3 ok --score
This does NOT submit the assignment! When you are satisfied with your score, submit the assignment to Gradescope to receive credit for it.
Submit Assignment
Submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment. Lab 00 has detailed instructions. Correctly completing all questions is worth one point for regular section students and two points for mega section students.
If you are in regular section, be sure to fill out your TA's attendance form before you leave section. Attending lab section is worth one point for regular section students.
Optional Questions
These questions are optional. If you don't complete them, you will still receive credit for this assignment. They are great practice, so do them anyway!
Q7: Two of Three
Write a function that takes three positive numbers as arguments and returns the sum of the squares of the two smallest numbers. Use only a single line for the body of the function.
def two_of_three(i, j, k):
"""Return m*m + n*n, where m and n are the two smallest members of the
positive numbers i, j, and k.
>>> two_of_three(1, 2, 3)
5
>>> two_of_three(5, 3, 1)
10
>>> two_of_three(10, 2, 8)
68
>>> two_of_three(5, 5, 5)
50
"""
return _____
Hint: Consider using the
max
ormin
function:>>> max(1, 2, 3) 3 >>> min(-1, -2, -3) -3
Use Ok to test your code:
python3 ok -q two_of_three
Use Ok to run the local syntax checker (which checks that you used only a single line for the body of the function):
python3 ok -q two_of_three_syntax_check
Q8: Middle Number
Implement middle
by writing a single return expression that evaluates to the
value that is neither the largest or smallest among three different integers
a
, b
, and c
.
Hint: Try combining all the numbers and then taking away the ones you don't want to return by using the built-in
min
andmax
functions.>>> max(1, 2, 3) 3 >>> min(-1, -2, -3) -3
def middle(a, b, c):
"""Return the number among a, b, and c that is not the smallest or largest.
Assume a, b, and c are all different numbers.
>>> middle(3, 5, 4)
4
>>> middle(30, 5, 4)
5
>>> middle(3, 5, 40)
5
>>> middle(3, 5, 40)
5
>>> middle(30, 5, 40)
30
"""
return ____
Use Ok to test your code:
python3 ok -q middle
Q9: Largest Factor
Write a function that takes an integer n
that is greater than 1 and
returns the largest integer that is smaller than n
and evenly divides n
.
def largest_factor(n):
"""Return the largest factor of n that is smaller than n.
>>> largest_factor(15) # factors are 1, 3, 5
5
>>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
40
>>> largest_factor(13) # factors are 1, 13
1
"""
"*** YOUR CODE HERE ***"
Hint: To check if
b
evenly dividesa
, use the expressiona % b == 0
, which can be read as, "the remainder when dividinga
byb
is 0."
Use Ok to test your code:
python3 ok -q largest_factor
Q10: Multiple
Write a function that takes in two numbers and returns the smallest number that
is a multiple of both.
def multiple(a, b):
"""Return the smallest number n that is a multiple of both a and b.
>>> multiple(3, 4)
12
>>> multiple(14, 21)
42
"""
"*** YOUR CODE HERE ***"
Use Ok to test your code:
python3 ok -q multiple