\( \newcommand{\NOT}{\neg} \newcommand{\AND}{\wedge} \newcommand{\OR}{\vee} \newcommand{\XOR}{\oplus} \newcommand{\IMP}{\Rightarrow} \newcommand{\IFF}{\Leftrightarrow} \newcommand{\TRUE}{\text{True}\xspace} \newcommand{\FALSE}{\text{False}\xspace} \newcommand{\IN}{\,{\in}\,} \newcommand{\NOTIN}{\,{\notin}\,} \newcommand{\TO}{\rightarrow} \newcommand{\DIV}{\mid} \newcommand{\NDIV}{\nmid} \newcommand{\MOD}[1]{\pmod{#1}} \newcommand{\MODS}[1]{\ (\text{mod}\ #1)} \newcommand{\N}{\mathbb N} \newcommand{\Z}{\mathbb Z} \newcommand{\Q}{\mathbb Q} \newcommand{\R}{\mathbb R} \newcommand{\C}{\mathbb C} \newcommand{\cA}{\mathcal A} \newcommand{\cB}{\mathcal B} \newcommand{\cC}{\mathcal C} \newcommand{\cD}{\mathcal D} \newcommand{\cE}{\mathcal E} \newcommand{\cF}{\mathcal F} \newcommand{\cG}{\mathcal G} \newcommand{\cH}{\mathcal H} \newcommand{\cI}{\mathcal I} \newcommand{\cJ}{\mathcal J} \newcommand{\cL}{\mathcal L} \newcommand{\cK}{\mathcal K} \newcommand{\cN}{\mathcal N} \newcommand{\cO}{\mathcal O} \newcommand{\cP}{\mathcal P} \newcommand{\cQ}{\mathcal Q} \newcommand{\cS}{\mathcal S} \newcommand{\cT}{\mathcal T} \newcommand{\cV}{\mathcal V} \newcommand{\cW}{\mathcal W} \newcommand{\cZ}{\mathcal Z} \newcommand{\emp}{\emptyset} \newcommand{\bs}{\backslash} \newcommand{\floor}[1]{\left \lfloor #1 \right \rfloor} \newcommand{\bigfloor}[1]{\Big \lfloor #1 \Big \rfloor} \newcommand{\ceil}[1]{\left \lceil #1 \right \rceil} \newcommand{\bigceil}[1]{\Big \lceil #1 \Big \rceil} \newcommand{\abs}[1]{\left | #1 \right |} \newcommand{\bigabs}[1]{\Big | #1 \Big |} \newcommand{\xspace}{} \newcommand{\proofheader}[1]{\underline{\textbf{#1}}} \)

CSC110 Practice Problems: Data and Functions

We have covered a lot this first couple of weeks! Now is your chance to a pause, review, and practice what you’ve learned. In these exercises, you’ll review Python’s built-in data types and functions and use them to define new functions of your own. You’ll practice the skill of reading Python error messages, which helps you identify problems in your code all throughout this term. Finally, you’ll explore how to use Python’s built-in data types to represent colour data and write several functions that operate on this new kind data to produce some pretty neat images.

Tip: even if you plan on doing most of your work on the computer, we recommend keeping some paper around to write rough work on whenever you’re doing practice problems like these.

Exercise 0: Software setup

You should have already setup the necessary software for CSC110. In case you haven’t, please complete the Software Installation Guide linked on the front page of the Quercus. If you get stuck or have any questions, be sure to ask on Ed or visit office hours ASAP.

Exercise 1: Reviewing Python’s data types and functions

For each of the following expressions, write the expression’s value below it. (This is what you would see if you pressed “Enter” after typing in the expression in the Python console).

Do this by hand first, and then check your answer in the Python console.

# Question 1
>>> 3 + 5 * 1.5




# Question 2
>>> ((7 // 2) ** 3) % 4




# Question 3
>>> 'Da' + 'vid'




# Question 4
>>> numbers = [0, 2, 4, 6, 9]
>>> [x % 2 for x in numbers]




# Question 5
>>> numbers = [0, 2, 4, 6, 9]
>>> {x % 2 for x in numbers}




# Question 6
>>> numbers1 = [10, 20, 40, 60, 90]
>>> numbers2 = [1, 3, 1]
>>> combos = [x + y for x in numbers2 for y in numbers1]
>>> len(combos)



# Question 7
>>> {x * 3 for x in range(3, 6)}




# Question 8
>>> numbers1 = {0, 2, 4, 6, 9}
>>> numbers2 = {0, 2, 7, 6, 5}
>>> numbers1.union(numbers2)




# Question 9
>>> strings = ['cat', 'dog', 'meow', 'woof']
>>> strings[0] + strings[1] + strings[2] + strings[3]




# Question 10
>>> strings = ['cat', 'dog', 'meow', 'woof']
>>> strings[0][0] + strings[1][0] + strings[2][0] + strings[3][0]
# Hint: strings[0][0] is the same as (strings[0])[0], i.e., find the value
# of strings[0] first, and then perform the [0] indexing operation on it.



Exercise 2: Practice writing functions

In this part, you’ll gain some practice writing some simple functions in Python. We have chosen these functions to help you review all of the basic data types covered in this course. Please download the following starter file and save it into your csc110/practice folder:

Then, open your csc110 folder in PyCharm, navigate to the practice1.py file in the practice folder and open it. Follow the instructions under “Exercise 2” to complete the functions in that section.

Exercise 3: Debugging corner

The process of debugging, going and correcting the program and then looking at the behaviour, and then correcting it again, and finally iteratively getting it to a working program, is in fact, very close to learning about learning.

–Nicholas Negroponte

We all strive to write code without any errors at all, but we are all human and make mistakes. The mark of a mature programmer is not the ability to write code without errors, but the ability to identify and resolve errors as they come up. In this exercise, you practice learning about the various kinds of errors that you can encounter in Python just using the parts of the language we’ve learned this past week. (There are more than you might expect!)

Each of the sections below include snippets of code that have some kind of error. We have included the message that Python displays when you try to run this code.

Instructions

For each of the code examples shown below:

  1. Read the code that was typed into the Python console, and the resulting error message. (Note: to help you focus on the message text, we’ve omitted some additional error info that you’d see if you typed these expressions into the Python Console in PyCharm.)

  2. Identify the problem, and explain it.

    • Remember that you can work on these practice problems with a friend from the class. If you’re doing so, we suggest taking turns with your partner explaining each error.
  3. Write a corrected version of the code that can be evaluated successfully in the Python console.

Read both the code and the error message carefully. Figure out what the error is and how to fix it (if possible). Some of the error messages can be a little cryptic, so don’t hesitate to ask us on Ed or during office hours for a hint if you get stuck.

You can also download a Python file containing all of the code snippet in the starter file practice1_debugging.py (Right-click the link and select “Save Link As…”, then save this into your csc110/practice folder as well).

Syntax errors: when the Python interpreter can’t read your code

A syntax error is an error in how a piece of Python code is written that prevents Python from running the code at all. Syntax errors are reported using an error type called SyntaxError. They can be frustrating to resolve when you are first starting out because they don’t allow you to run your program. Syntax errors are often caused by small typos, misplaced or missing punctuation, and misspellings, which makes them hard to identify by beginners at a glance.

>>> 5 = x
  File "<stdin>", line 1
SyntaxError: cannot assign to literal
>>> numbers = [1 2 3]
  File "<stdin>", line 1
    numbers = [1 2 3]
                 ^
SyntaxError: invalid syntax
>>> fruit_to_color = {
...   'banana': 'yellow',
...   'kiwi': 'green'
...   'blueberries': 'blue'}
  File "<stdin>", line 4
    'blueberries': 'blue'}
                 ^
SyntaxError: invalid syntax
>>> result0 = max{3, 4}
  File "<stdin>", line 1
    result0 = max{3, 4}
                 ^
SyntaxError: invalid syntax

Name errors: when variables don’t exist

Another common error caused by typos is a NameError. A NameError occurs when you refer to a variable (or function) name that does not exist.

>>> my_number = 10
>>> result1 = 15 + my_nubmer
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'my_nubmer' is not defined
>>> result2 = Sum([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Sum' is not defined

Type errors: invalid uses of operations and functions

A TypeError most commonly occurs when you attempt to use an operation on argument(s) of incompatible types. As you gain more experience in Python, you become very familiar with which operations can be used with which types.

>>> result3 = [1, 2, 3] + 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> numbers = {1, 2, 3}
>>> result4 = numbers[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not subscriptable
>>> x = [1, 2, 3]
>>> result5 = x[2.5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not float

Other errors

Here are a few other common errors you may encounter in Python. We aren’t going to describe these here: instead, use each error message to determine the cause of the error.

>>> nums = [110, 111, 200]
>>> n0 = nums[0]  # 110
>>> n1 = nums[1]  # 111
>>> n2 = nums[2]  # 200
>>> n3 = nums[3]  # Error!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> result6 = 1 // 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> empty_list = []
>>> result7 = max(empty_list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence

Conclusion

Being able to understand error messages is an important programmer skill. We have compiled a list of many common errors, along with a brief description for each error, in A.4 Python Exceptions Reference.

Exercise 4: Representing colour data

In our first week, we learned about the common Python data types that will serve as the foundation for how we represent all kinds of data in this course. In this exercise, we are going to learn how to use these basic data types to represent a more complex form of data: colours. Note: This exercise will be good practice for your upcoming first assignment!

Reading

As a first step, please read the Course Notes 1.8 Application: Representing Colour. This will go over some theory on how we represent colours in a computer program.

Then, answer the following questions about the RGB24 colour model:

  1. For the colour [51, 200, 3], what is the red amount in the colour? The green amount? The blue amount?

  2. What colour does [0, 0, 0] represent? What about [255, 255, 255]?

  3. How many different colours can be represented using the RGB24 colour model?

  4. A greyscale colour is one that has the same value for its red, green, and blue amounts. Greyscale colours get their name from the fact that when the red, green, and blue components are equal, the colour looks grey—devoid of colour entirely.

    How many greyscale colours can be represented in the RGB24 colour model?

Programming with colour

Now that you’ve read about the RGB24 colour model, let’s see how to apply it in Python.

Download the following starter file and save it into your csc110/practice folder:

This is a file we’ve written to help visualize some colours using the pygame library, which we will learn about throughout this course. For now, you do not need to understand the code in practice1_colours.py, just make sure it is saved in your practice folder. Now, let’s get started with a warm-up:

  1. Make sure practice appears as a blue folder in the Project View. If it does not, right-click on the folder and select Mark Directory as -> Sources Root.

  2. Run practice1.py in the Python console (right-click -> “Run File in Python Console”).

  3. Type in the Python statement import practice1_colours (no .py).

    >>> import practice1_colours

    This loads the code inside the file you downloaded.

    Note: this import raises an error if you have not installed pygame on your computer (this is one of the Python libraries you installed as part of the software setup instructions).

  4. We are going to use the function called show_colours from practice1_colours.py to visualize some colours. To learn how, first call the built-in function help on show_colours:

    >>> help(practice1_colours.show_colours)
    show_colours(colours)
        Visualize the given list of colours using Pygame.
        ...

    Pretty cool! help displays the docstring for show_colours, so we can read it to understand how to use this function without getting distracted by the code in its body.

    Read through the docstring carefully, and make sure you understand both how colours are being represented and how they are passed to show_colours.

  5. Try typing/copying the doctest example from show_colours into the Python console, except use practice1_colours.show_colours(...) instead of show_colours(...).

    You should see a Pygame window appear, showing a few different colours.

Next, you should complete the functions in practice1.py, each of which returns a list of colours. We have ordered these functions in increasing complexity, so you should test each function in the Python console before moving onto the next one. To test a function, you can use the same approach as the above demo, except call the function to define the variable colours. (Don’t forget to import practice1_colours each time. Tip: you can press the up arrow in the Python console to view previous expressions/statements.)

Some sample images are shown here, but yours may look different depending on the colours you choose. Experiment to find the colour combinations you like best!

  1. my_favourite_colours: return a list of around 5–7 colours that you think look pretty, from this Wikipedia table of colours. The “Decimal” column tells you the RGB values of each colour.

  2. stripes: given two colours and a positive integer n, return a list of length 2n that repeats the colours in an alternating pattern (colour 1, colour 2, colour 1, colour 2, etc.).

    Hint: Python supports the operation of multiplying a list by a positive integer to repeat that list.

    >>> [1, 2] * 5
    [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
    Sample image of Pygame stripes
  3. rgb_combinations: given a set of integers in the range 0–255, return a list of colours of every possible combination of RGB values from the given set.

    Hint: review how we defined the Cartesian product in Python (Course Notes Section 1.7), and extend this to a list of three values instead of two.

    Sample image of Pygame colour combinations
  4. gradient: given two colours and a positive integer n, return a list of length n + 1 that contains the colours in a linear gradient between the given colours.

    A gradient is a sequence of colours that transforms from one colour to another. For two colours \((r_0, g_0, b_0)\) and \((r_1, g_1, b_1)\), and a given \(n\), the \(i\)-th colour in the gradient has value \((r(i), g(i), b(i))\), where:

    \[r(i) = r_0 + \bigfloor{\frac{i}{n} (r_1 - r_0)}\] \[g(i) = g_0 + \bigfloor{\frac{i}{n} (g_1 - g_0)}\] \[b(i) = b_0 + \bigfloor{\frac{i}{n} (b_1 - b_0)}\]

    We use \(\floor{\cdot}\) to represent the mathematical floor function, which rounds down to the nearest integer. \(i\) ranges from \(0\) to \(n\), which results in \(n + 1\) values.

    Hints: we leave it up to you whether to write separate function(s) to compute the \(r(i)\), \(g(i)\), and/or \(b(i)\) values.

    To round down a float to the nearest integer, you can call int on it:

    >>> int(1.8)
    1
    Sample image of Pygame gradient

Additional exercises

  1. Function practice. Complete the implementation of the following functions.

    1. def sum_in_list(num1: float, num2: float, lst: list) -> bool:
          """Return whether the sum of num1 and num2 is in lst (a list of floats).
      
          >>> sum_in_list(2.0, 3.5, [1.1, 3.3, 5.5, 7.7])
          True
          >>> sum_in_list(-10.1, 23.6, [])
          False
          """
  2. More practice with error messages. Here are two function definitions that have syntax errors. For each one:

    1. Copy the code into a Python file and run the file.
    2. Read the error message that is displayed.
    3. Identify the problem in the code and explain it.
    4. Fix the problem so that you have a working function definition.
    def is_same_length(list1: list, list2: list) -> bool
        """Return whether list1 and list2 have the same length.
        """
        return len(list1) == len(list2)
    def is_much_greater(num0: int, num2: int) -> bool:
    return num0 >= 2 * num2

    Note: the second function definition also has a syntax error, but Python uses the more specific name IndentationError to categorize this specific kind of syntax error.

  3. Errors within function definitions.

    def repeat(string: str) -> str:
        return s + s
    
    
    >>> result = repeat('Hello')
    Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "<stdin>", line 2, in repeat
    NameError: name 's' is not defined

    Notice that in this code snippet, an error occurs when the function repeat is called, not when it is defined. The second-last line of the error message, File "<stdin>", line 2, in repeat, tells you exactly what line the error occurred in.

    def add_incorrect(n: int) -> int:
        return n + 'one'
    
    
    >>> result = add_incorrect(3)
    Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "<stdin>", line 2, in add_incorrect
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
  4. More with colours. Define one more function waves that, given two colours and an integer n, returns a “wave gradient” pattern that alternates between the two given colours n times.

    This is a nice challenge that combines multiple elements of the exercises in this handout, together in a single function. We are deliberately leaving this one more open for you to explore, and please ask for pointers if you get stuck!

    Sample image of Pygame waves