Try   HackMD

Drill 12 Solution

Question 1

Given this function:

def if_statement(a, b):
    c = 10
    d = 10
    if (a < 5):
        c = 4
        d = 3
    else:
        if (b > 3):
            c = 5
            d = 5

    return c + d

What will the function return given the arguments 5 for a and 5 for b?

( ) 7
( ) 10
( ) 20
( ) 14

Answer

10

Unlike Pyret, where you used if-expressions, in Python you can create if-statements. The difference is that in Pyret, an if-expression needed to evaluate to a single value, whereas in Python, an if-statement just checks if a given condition is true or false and runs the appropriate code.

Question 2

Fill in the blanks for this Python function such that it returns the string "hello Professor Kathi".

​[Blank1] function(name):
​   a = "[Blank2]"
​   b = " Professor "
​   [Blank3] a + [Blank4] + name

function([Blank5])
Answer

Blank1: def

Blank2: hello

Blank3: return

Blank4: b

Blank5: "Kathi"

In Pyret, every function evaluates to a certain value. In Python, if you want a function to return a piece of data you need to explicitly write return.

Question 3

Given this code:

a = 5
b = 9
c = 4
a = b

What is the value of the variable a?

( ) Python throws an error data is immutable and cannot be changed.
( ) Python throws an error the name b cannot be the value of a.
( ) 5
( ) 9

Answer

9

Python makes use of variables names of data that can be reassigned and mutated.

Question 4

Given this list of letters,

letters = ['a', 'b', 'c']

Fill in the blank to add the string 'd' to letters:

letters.________('d')
Answer

append

The list method append adds a piece of data to the end of a list.

Question 5

Given this list of letters:

letters = ['a', 'b', 'c']

Which of the following lines of code correctly gets 'b' from the list?

( ) letters['b']
( ) letters[2]
( ) letters.get('b')
( ) letters[1]

Answer

letters[1]

To access the data from a list at index i, write list[i]