By the end of this lab, you should have submitted the lab01
assignment using the command submit lab01
.
This lab is due by 11:59pm on 06/26/2014.
Here is a lab01.py starter file for this lab.
Sometimes, you can append certain "flags" on the command line to inspect your code further. Here are a few useful ones that'll come in handy this semester. If you want to learn more about other python flags, you can look at the documentation.
python3 FILE_NAME
-i
: The -i
option runs your Python script, and throws you into an interactive session. If you omit the -i
option, Python will only run your script. See the next section regarding interactive sessions to learn more!
python3 -i FILE_NAME
-m doctest
: Using -m doctest
option will be useful on your homeworks and projects to help you test your code by showing you whether your code is working as you intend it to. Doctests are marked by triple quotations (""") and are usually located within the function.
python3 -m doctest FILE_NAME
-v
: The -v
flag signifies a verbose option. You can append this flag to the -m doctest
flag to be notified of all results (both failing and passing tests).
python3 -m doctest -v FILE_NAME
Let's compare the ideas of true division (single slash /
in Python;
does decimal division), floor division (double slash //
in Python;
rounds down to the nearest integer), and modulo (percent sign %
in
Python; similar to a remainder):
True Division (decimal division):
>>> 1 / 4
0.25
>>> 4 / 2
2.0
>>> 11 / 3
3.6666666666666665
Floor Division (integer division):
>>> 1 // 4
0
>>> 4 // 2
2
>>> 11 // 3
3
Modulo (similar to a remainder):
>>> 1 % 4
1
>>> 4 % 2
0
>>> 11 % 3
2
Notice that we can check whether x
is divisible by y
by checking
if x % y == 0
.
What would Python print? Try to figure it out before you type it into the interpreter!
>>> a, b = 10, 6
>>> a != 0 and b > 5
______True
>>> a < b or not a
______False
>>> not not a
______True
>>> not (not a or not not b)
______False
What do you think the following expression evaluates to?
True and not False or not True and False
It turns out that Python interprets that expression in the following way:
(True and (not False)) or ((not True) and False)
Failing to use parentheses is one of the easiest ways for you to break your program - it is very easy to misunderstand how Python will understand your expression if you don't have parentheses.
Boolean operators, like arithmetic operators, have an order of operation:
not
has the highest priorityand
or
has the lowest priorityIn Python, and
and or
are examples of short-circuiting operators.
Consider the following code:
10 or 1 / 0 != 1
Notice that if we just evaluate 1 / 0
, Python will raise an error,
stopping evaluation altogether!
However, the original line of code will not cause any errors — in
fact, it will evaluate to 10
. This is made possible due to
short-circuiting, which works as follows:
and
statements, Python will go left to right until it runs
into the first value that is false-y — then it will immediately
evaluate to that value. If all of the values are truth-y, it
returns the last value.or
statements, Python will go left to right until it runs
into the first value that is truth-y — then it will immediately
evaluate to that value. If all of the values are false-y, it
returns the last value.>>> True and 1 / 0 == 1 and False
______ZeroDivisionError
>>> True or 1 / 0 == 1 or False
______True
>>> True and "Anything"
______'Anything'
>>> False or "Something"
______'Something'
>>> 1 and 3 and 6 and 10 and 15
______15
>>> "" or 0 or False or "Andrew and Rohin" or "The TA's" or 1 / 0
______'Andrew and Rohin'
The following snippet of code doesn't work! Figure out what is wrong and fix the bugs.
def both_positive(x, y):
""" Returns True if both x and y are positive and False
otherwise.
>>> both_positive(-1, 1)
False
>>> both_positive(1, 1)
True
>>> both_positive(0, 0)
False
"""
return x and y > 0
The line x and y > 0
is incorrect. It should be
return x > 0 and y > 0:
The original line will check that two things are true:
x
y > 0
When will x
be considered True? In Python, any number that is not 0
is considered True. Thus, the first doctest will fail: x = -1
and -1 != 0
, and y = 1 > 0
, so both clauses are True.
Disneyland is having a special where they give discounts for
grandparents accompanying their grandchildren. Help Disneyland figure
out when the discount should be given. Define a function
gets_discount
that takes two numbers as input (representing the two
ages) and returns True
if one of them is a senior citizen (age at
least 65) and the other is a child (age no more than 12). You should
not use if
in your solution.
def gets_discount(x, y):
"""Returns True if this is a combination of a senior citizen
and a child, False otherwise.
>>> gets_discount(65, 12)
True
>>> gets_discount(9, 70)
True
>>> gets_discount(40, 45)
False
>>> gets_discount(40, 75)
False
>>> gets_discount(65, 13)
False
>>> gets_discount(7, 9)
False
>>> gets_discount(73, 77)
False
>>> gets_discount(80, 13)
False
>>> gets_discount(10, 25)
False
"""
"*** YOUR CODE HERE ***"
def gets_discount(x, y):
return (x <= 12 and y >= 65) or (x >= 65 and y <= 12)
Define a function is_factor
that checks whether its first argument
is a factor of its second argument. We will assume that 0
is not a
factor of any number but any non-zero number is a factor of 0
.
You should not use if
in your solution.
def is_factor(x, y):
"""Returns True if x is a factor of y, False otherwise.
>>> is_factor(3, 6)
True
>>> is_factor(4, 10)
False
>>> is_factor(0, 5)
False
>>> is_factor(0, 0)
False
>>> is_factor(10, 2)
False
"""
"*** YOUR CODE HERE ***"
def is_factor(x, y):
return x != 0 and y % x == 0
Predict what Python will print in response to each of these expressions. Then try it and make sure your answer was correct, or if not, that you understand why!
>>> z, y = 1, 2
>>> print(z)
______1
>>> def square(x):
... print(x * x) # Hit enter twice
...
>>> a = square(2)
______4
>>> print(a)
______None
>>> def square(y):
... return y * y # Hit enter twice
...
>>> a = square(2)
>>> print(a)
______4
>>> a, b = 10, 6
>>> if a == 4:
... 6
... elif b >= 4:
... 6 + 7 + a
... else:
... 25
...
______23
else
Consider the following function:
>>> def abs(x):
... if x >= 0:
... return x
... else:
... return -x
...
It is correct to rewrite abs
in the following way:
>>> def abs(x):
... if x >= 0:
... return x
... return -x # missing else statement!
...
This is a direct consequence of how return
works — when
Python sees a return
statement, it will immediately terminate the
function, and the rest of the function will not be evaluated. In the
above example, if x >= 0
, Python will never reach the final line.
Try to convince yourself that this is indeed the case before moving on.
Keep in mind that omitting the else
only works if the function is
terminated! For example, the following function will always print
"less than zero", because the function is not terminated in the body
of the if
suite:
>>> def foo(x):
... if x > 0:
... print("greater than zero")
... print("less than zero")
...
>>> foo(-3)
less than zero
>>> foo(4)
greater than zero
less than zero
In general, omitting the else
will make your code more concise —
however, if you find that it makes your code harder to read, by all
means use an else
statement.
The following snippet of code doesn't work! Figure out what is wrong and fix the bugs.
def compare(a, b):
""" Compares if a and b are equal.
>>> compare(4, 2)
'not equal'
>>> compare(4, 4)
'equal'
"""
if a = b:
return 'equal'
return 'not equal'
The line a = b
will cause a SyntaxError
. Instead, it should be
if a == b:
>>> n = 3
>>> while n >= 0:
... n -= 1
... print(n)
...
______2
1
0
-1
>>> n, i = 7, 0
>>> while i < n:
... i += 2
... print(i)
...
______2
4
6
8
>>> # typing Ctrl-C will stop infinite loops
>>> n = 4
>>> while True:
... n -= 1
... print(n)
...
______3
2
1
0
-1
-2
... # continues forever
______
# Q4
>>> n = 2
>>> def exp_decay(n):
... if n % 2 != 0:
... return
... while n > 0:
... print(n)
... n = n // 2
...
>>> exp_decay(64)
______64
32
16
8
4
2
1
>>> exp_decay(5)
______# No output
Define a function factors(n)
which takes in a number, n
, and
prints out all of the numbers that divide n
evenly. For example, a
call with n = 20
should result as follows:
def factors(n):
"""
Prints out all of the numbers that divide `n` evenly.
>>> factors(20)
20
10
5
4
2
1
"""
"*** YOUR CODE HERE ***"
def factors(n):
x = n
while x > 0:
if n % x == 0:
print(x)
x -= 1