01.04 - Python Exercises

Exercises rating:

★☆☆ - You should be able to do it based on Python knowledge plus the text.

★★☆ - You will need to do extra thinking and some extra reading/searching.

★★★ - The answer is difficult to find by a simple search, requires you to do a considerable amount of extra work by yourself (feel free to ignore these exercises if you're short on time).

1. Create a function which has a default argument, here is a test for the function. (★☆☆)

This will be a pattern in some exercises. The exercise will fail when you run it. And the objective will be to change the code above the # test indicator until the code below the # test indicator do not fail anymore.

In [ ]:
# define function here
def my_func():
    pass


# test
print(my_func('positional', 'optional'))
print(my_func('positional'))

2. Write a function that receives an arbitrary number of arguments and prints them. (★☆☆)

Note that we do not specify whether these arguments are positional or keyword arguments. For the extra challenge you may wish to accept and arbitrary number of both types of arguments.

In [ ]:
 

3. Call the function above using the list and dictionary provided below. (★☆☆)

In [ ]:
args = [1, 'two', 3.14]
kwargs = {'pinkie': 'pie', 'rainbow': 'dash'}

4. Rewrite the below function into a list comprehension. (★☆☆)

You can run the first cell to define the function in the notebook state. Then use the add_five function to check whether your list comprehension gives the same result.

In [ ]:
def add_five(numbers):
    l = []
    for num in numbers:
        l.append(num + 5)
    return l
In [ ]:
numbers = [1,2,3]


# list comprehension

5. Print the type of type (yes, this makes sense :) ). (★★☆)

In [ ]:
 

6. In the text below, how often each word appears? (Use list comprehensions.) (★★☆)

There is no need to count or remove punctuation, although for extra challenge you may wish to remove the dots and commas.

In [ ]:
lorem_ipsum = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""

7. Write a sum function that takes an arbitrary number of parameters and can sum numbers or concatenate strings. (★★☆)

If only numbers are given the function will sum them up. If only strings are given the function will concatenate them all. If both strings and numbers are given it is fine to raise an error. But what if no arguments are given? That's up to you.

In [ ]:
def my_sum(*args):
    pass