Solutions

Combining Strings

def fence(original, wrapper):
    new_string = wrapper + original + wrapper
    return new_string

Your pseudocode might look like:

  1. Define function with two parameters original and wrapper
  2. Combine the parameters into a new string the order: wrapper, original
  3. Return the new string

Return versus print

Python will first execute the function add with a = 7 and b = 3, and, therefore, print 10. However, because function add does not have a line that starts with return (no return “statement”), it will, by default, return nothing which, in Python world, is called None. Therefore, A will be assigned None and the last line (print(A)) will print None. As a result, we will see:

10
None

If we want to return the value rather than print it we must replace print in our function with return.

Calling by name

  1. 2003/2/1
  2. 2018/11/21
  3. Using named arguments can make code more readable since one can see from the function call what name the different arguments have inside the function. It can also reduce the chances of passing arguments in the wrong order, since by using named arguments the order doesn’t matter.

The Old Switcheroo

3 7 is the correct answer. Initially, a has a value of 3 and b has a value of 7. When the swap function is called, it creates local variables (also called a and b in this case) and trades their values. The function does not return any values and does not alter a or b outside of its local copy. Therefore the original values of a and b remain unchanged.

If we want to swap two values in Python we need to use something like the following

a = 3
b = 7

def swap(a, b):
    return b, a

a, b = swap(a, b)

print(a, b)

This reverses the order of the parameters when they are returned and does swap the two values.

Find the First

Your function should look something like:

def first_negative(values):
    for v in values:
        if v<0:
            return v

What happens if you pass an empty list is passed to this function? What happens if all the values are positive?