Assignment 2
This is an ungraded assignment!
Deadline: 1st Oct - 15:00 - After this time, don't change your notebook. It'll be automatically collected by CoCalc.
We will use this assignment to simulate how a graded assignment works. On the deadline, we'll automatically collect your assignment and calculate the points. As an answer, you will receive a report showing the test cases where you succeeded and the final number of points. However, remember, as this is a non-graded assignment, those points won't count for your grade.
What to do if you get stuck with a task?
- Ask for help in the Monday session
- Ask for help in the Friday session
- Ask for help on the course forum
- E-Mail your tutor
- Ask for help on Stack Overflow. Before asking there you should read the following links, or your question will probably be closed. There is a high chance you can find a solution for your problem in one of the many existing answers on the site.
Task 0 (0 Points)
Write code that prints the string 'Hello world'.How to read error messages and debug on CoCalc
There will be times when you see an error message because of something being wrong in your code.This is completely normal!
A lot of the time when programming is spent fixing errors in the code or looking for more efficient solutions. So there will definitely be times during this course when you run into errors. But how can you understand and fix them?---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-57dabf8ad525> in <module>
1 number = 3 * 5
----> 2 print(num)
NameError: name 'num' is not defined
The cell above shows such an example. The stack trace / traceback is shown. The last line tells you that a NameError was encountered when your code was executed. We can check the Python documentation to see what this error means - link to the documentation: NameError - or we can read the message that is included with it: name 'number' is not defined.
Above the error we can see the code that caused the error. In this case the error happened in line 2. Based on the code in that line and the error message we can see that the variable was not defined. When we tried to print it the error happened. To fix it can we can rename the variable in line 1 to or change the in line 2 to .
Task 1 (1 Point)
Define a variable s1.Success!
The following cell contains an example of what you see when your solution is wrong.
Big red scary box = something is wrong!
This is just here as an example to show you what it looks like. You don't have to change the code in the box to make it work or anything.
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-3-eedc3f8f4569> in <module>
1 from nose.tools import assert_true
----> 2 assert_true(False)
/usr/lib/python3.8/unittest/case.py in assertTrue(self, expr, msg)
763 if not expr:
764 msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
--> 765 raise self.failureException(msg)
766
767 def _formatMessage(self, msg, standardMsg):
AssertionError: False is not true
Here we see that the error is an AssertionError. The lower half of the stack trace shows us code that is called by the code that we have written. This useful when we are using code from other projects in our own projects. In this case we don't need it though.
The structure of the stack trace is that at the bottom it shows the line of code that caused the error, and then above that code block there can be more code blocks, with code that has caused the code in the lower block to be called.
In our example (from top to bottom): 'assert_true(False)' was executed in line 2, which caused the code in the lower half to be executed, where in line 765 an error happened.
The error further tells us that 'False is not true'. In the upper half we see that 'assert_true(False)' was executed in line 2. This means that the value inside 'assert_true()' should have been 'True' and not 'False'.
The tests that check your code will usually check that the value that your code calculated is the same as the correct answer. That way you can find out which value is wrong and by looking at your code then figure out why. Another example is given below.
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-10-6bf482eb6108> in <module>
7
8 from nose.tools import assert_equal
----> 9 assert_equal(c, 2) # check that 'c' has the value 2
/usr/lib/python3.8/unittest/case.py in assertEqual(self, first, second, msg)
910 """
911 assertion_func = self._getAssertEqualityFunc(first, second)
--> 912 assertion_func(first, second, msg=msg)
913
914 def assertNotEqual(self, first, second, msg=None):
/usr/lib/python3.8/unittest/case.py in _baseAssertEqual(self, first, second, msg)
903 standardMsg = '%s != %s' % _common_shorten_repr(first, second)
904 msg = self._formatMessage(msg, standardMsg)
--> 905 raise self.failureException(msg)
906
907 def assertEqual(self, first, second, msg=None):
AssertionError: 0 != 2
We get another 'AssertionError'. '0 != 2'. Again the lower half of the stack trace doesn't really help us. In the first block (from the top) we see our code, where we are checking that 'c' is equal to '2'. Because we get an 'AssertionError' we know that this is not the case, so 'c' is not equal to '2'. The error further tells us that apparently 'c' must be 0.
We can then look at our calculation code again and we see that we forgot to save the value of 'a / b' in the variable c! If we save the the value correctly in 'c' and run the cells again then the error will disappear, as our solution is now correct.
Play around with the code in the next cell and see how the error changes if you change the value for 'c'.
Task 2 (1 Point)
Change the type of the variable 'rating' to int.Success!
Task 3
For a circle of radius 3, display the diameter, circumference and area. Use the value 3.14159 for . Use the following formulas (r is the radius):Success!
Task 4
Use statements that change the value of the variable to if the variable is even and changes the value of the variable to if the variable is odd. You should use and for this task. Set the value of to or in your if-condition. You can use and if you need them, not just .Hint: Use the remainder operator (%, also known as modulo).
Success!
Success!
This cell should only be visible to tutors (hopefully).
The goal of Task 5 and 6 is to teach the students debugging / reading the stack traces.
Task 5 (4 Points, 1 Point per question)
What caused the error in the following code samples? Store your solution in a variable called . There is always only one correct solution.
This task uses hidden>hidden tests. You won't know if your solution is correct or not until it is graded and returned.
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-18-f76d16b615ef> in <module>
1 a = 5
2 b = a - 5
----> 3 a / b
ZeroDivisionError: division by zero
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-2b1c8c0f7ecc> in <module>
1 a = 5
----> 2 b = a - "5"
3 c = a / b
TypeError: unsupported operand type(s) for -: 'int' and 'str'
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-27-c7f455dea594> in <module>
5
6 from nose.tools import assert_equal
----> 7 assert_equal(c, 3)
/usr/lib/python3.8/unittest/case.py in assertEqual(self, first, second, msg)
910 """
911 assertion_func = self._getAssertEqualityFunc(first, second)
--> 912 assertion_func(first, second, msg=msg)
913
914 def assertNotEqual(self, first, second, msg=None):
/usr/lib/python3.8/unittest/case.py in _baseAssertEqual(self, first, second, msg)
903 standardMsg = '%s != %s' % _common_shorten_repr(first, second)
904 msg = self._formatMessage(msg, standardMsg)
--> 905 raise self.failureException(msg)
906
907 def assertEqual(self, first, second, msg=None):
AssertionError: '3' != 3
Task 6
What caused the error in the following code samples? Store your solution in a variable called . There is always only one correct solution.
This task uses hidden tests. You won't know if your solution is correct or not until it is graded and returned.
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-24-dc6fb09ca06e> in <module>
13 assert_true(a < 6)
14 assert_true(less_than_10)
---> 15 assert_true(less_than_6)
/usr/lib/python3.8/unittest/case.py in assertTrue(self, expr, msg)
763 if not expr:
764 msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
--> 765 raise self.failureException(msg)
766
767 def _formatMessage(self, msg, standardMsg):
AssertionError: False is not true
File "<ipython-input-27-7a45abec651c>", line 4
if a = 5:
^
SyntaxError: invalid syntax
Task 7 (1 Point)
Store every letter of the string 'Programming' in the variable . Add a space character after every letter.In the end, the variable should contain the value 'P r o g r a m m i n g '.
Don't forget the space character the final 'g'!
Hint: Use a for-loop for this task.
Hint: You can combine strings, or add characters to them, with "+". An example is given in the cell below.
Success!
Task 8 (1 Point)
Store every second letter of the string 'Programming' (starting at 'P') in the variable . Add a space character after every letter.In the end, the variable should contain the value 'P o r m i g '.
HINT: Use a for-loop for this task.
HINT: Count how many iterations of the for-loop have been executed and use that information to check whether you should include the character of the current iteration in the result or not.
Don't forget the space character the final 'g'!
Success!
Task 9 (3 Points)
Write code that counts how many operations you need to perform to reach 1 with the Collatz conjecture sequence, for . The example below has 6 steps. Store the number of steps required in a variable called .According to the Collatz conjecture the following sequence will always reach 1 for any positive integer:
if the integer is even then the next term in the sequence is half of the previous term
if the integer is odd then the next term in the sequence is 3 times the previous term plus 1
Example for n=10:
Step | Current term | Next term |
---|---|---|
1 | 10 | 5 (even, halve it) |
2 | 5 | 16 (uneven, multiply by 3 and add 1): |
3 | 16 | 8 (even, halve it) |
4 | 8 | 4 (even, halve it) |
5 | 4 | 2 (even, halve it) |
6 | 2 | 1 (we are finished) |
This sequence can be described like this, perform this operation until you reach 1:
Hint: Use a while-loop.
Hint: Use if-conditions inside the while-loop.
Hint: Use the remainder operator (%, also known as modulo).
Hint: Update the value of the variable in every loop-iteration (halve it if it is even, multiply by 3 and add 1 if it is odd).
Hint: You do not have to define new variables for this task. You can solve it with only and .
Hint: If you fail the test that checks your number of steps try replacing the example from above with . Add print() statements to check which steps your code is executing and how many steps it needs! The test cases don't care about whether or not you have print()s in your solution, they won't break a correct solution but it can be helpful to figure out what your code does.
Success!