Lab 01: Control Flow

Table of Contents

Deadline

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.

Python flags

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.

Division

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):

Notice that we can check whether x is divisible by y by checking if x % y == 0.

Boolean operators

Question 1

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
______
>>> a < b or not a
______
>>> not not a
______
>>> not (not a or not not b)
______

Boolean order of operations

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:

Short-circuit operators

In 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:

Question 2: What would Python print?

>>> True and 1 / 0 == 1 and False
______
>>> True or 1 / 0 == 1 or False
______
>>> True and "Anything"
______
>>> False or "Something"
______
>>> 1 and 3 and 6 and 10 and 15
______
>>> "" or 0 or False or "Andrew and Rohin" or "The TA's" or 1 / 0
______

Question 3

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:

  1. x
  2. 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.

Question 4

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)

Question 5

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

Question 6: What would Python print?

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)
______
>>> def square(x):
...     print(x * x)        # Hit enter twice
...
>>> a = square(2)
______
>>> print(a)
______
>>> def square(y):
...     return y * y        # Hit enter twice
...
>>> a = square(2)
>>> print(a)
______

if statements

Question 7: What would Python print?

>>> a, b = 10, 6
>>> if a == 4:
...     6
... elif b >= 4:
...     6 + 7 + a
... else: 
...     25
...
______

Omitting the 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.

Question 8

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:

while loops

Question 9: What would Python print?

>>> n = 3
>>> while n >= 0:
...     n -= 1
...     print(n)
...
______
>>> n, i = 7, 0
>>> while i < n:
...     i += 2
...     print(i)
...
______
>>> # typing Ctrl-C will stop infinite loops
>>> n = 4
>>> while True:
...     n -= 1
...     print(n)
...
______
... # continues forever
______
>>> n = 2
>>> def exp_decay(n):
...     if n % 2 != 0:
...         return
...     while n > 0:
...         print(n)
...         n = n // 2
...
>>> exp_decay(64)
______
>>> exp_decay(5)
______

Question 10

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