Week 2: Solutions

This notebook contains the solutions to the week 2 Beginner, Intermediate and Advanced exercises.

Table of Contents

Beginner: If Statements

Question 1: The answer to this question is given below:

Demonstrator Notes: This question aims to give students their first practice with if statements. If a student is struggling, check in with them regularly and recap strings and the len() function as needed.

Question 2: The code for this question is below.

Demonstrator Notes: Please be mindful that some students may not be familiar with the pH scale, either because they have not studied Chemistry recently or because they learned it using different terms or acronyms. Before explaining the code, check that they understand the context - they might not say anything if they are confused.

Question 3: The problem with this code is that the boolean for the if evaluates as True when the temperature exceeds 100, so the elif is never executed. A simple solution would be to switch the order of the clauses like so:

Demonstrator Notes: The students have been given a similar example, where the solution is to reorder the clauses, in the Worked Example: Determining a Leap Year section. If students are struggling with this question, please suggest they re-read this section before providing them with the answer.

Question 4: The code for this question is below:

Demonstrator Notes: Many students will not immediately think to add up the days in each month in the manner the above code has. Because of the unfamiliar logic, be ready to guide them step by step and ‘’hold their hands’’ a bit more than usual for this question.

Question 5: One potential solution to this question is given below:

Demonstrator Notes: Many students may struggle here because they have forgotten, or never fully grasped, the % operator. Make sure they understand this operator before giving the answer, explaining it in terms of modular/“clock” arithmetic if necessary.

Question 6: An answer to this question is given below.

Demonstrator Notes: Last year, many students really struggled with unit conversions. Check they are doing distance_km / 1.60934 instead of distance_km*1.60934.

Question 7: A solution to this question is given below:

Question 7: This question may feel daunting to students at first. In reality, the solution only requires adding the first clause (year % 400 == 0). One way to help is to have students test a few example years on paper before coding so the logic becomes clearer. Only encourage them to start coding once you feel they have a strong conceptual grasp of the problem.

Question 8: The pass statement is a placeholder which effectively does nothing. If it were not there, we would have a SyntaxError as the if statement must contain code.

Demonstrator Notes: This question has two purposes. First, it introduces students to the pass statement, which they will need later in the course. Second, and more importantly, it encourages them to practice using documentation and independent research. Prompt students to look up the answer online rather than giving it to them directly.

Question 9: An answer to this question is given below:

Demonstrator Notes: This is a classic introduction to coding task. If student’s are struggling encourage them to search for FizzBuzz exercise python online. They will find lots of good advice which does not instantly give them the answer.

Question 10: The desired answer is below:

An alternative is given by:

Demonstrator Notes: Below is a step-by-step solution to reducing this problem. First, note that we can combine the x < 4, x < 15 and x > 30 cases to get:

Next, note that the final elif should never be evaluated as if z < -1 then z < 0, so the if is executed instead.

We can now combine the innermost if and else as follows:

Now, note that the z > 20 can’t ever be evaluated True, as if we are inside the outer if then z < 0.

We can now combine the inner if and elif:

By combining the outer if and inner statements, we now get the result.

Intermediate: Match Statements

Question 1: The answer to this question is given below:

Demonstrator Notes: This question aims to give the students pratice with the match statement. Before offering help, it might be worth checking that they understand the context for this question. Before offering help, check that they understand the context: less mathematical students, or non-native speakers, may not feel confident with terms like “Cartesian plane” or “quadrant.”

Question 2: The solution to this question is given below:

Demonstrator Notes: Because this example looks very similar when written with if statements, students may wonder what the point of match is. Point them to the section Converting Long elif Statements to match, which provides a more compelling example and highlights the advantages of match in certain situations.

Question 3: A model answer is given below:

Demonstrator Notes: A common mistake here is confusing operators with their string forms - for example, writing "*" instead of *, or the reverse.

Question 4: An example solution is provided below:

Demonstrator Notes: See the notes on Beginner Question 6 about unit conversion. In this question, some students may try to code every possible pair of conversions separately (e.g. GBP -> USD, GBP -> EUR, … , EUR -> JPY). Discourage this, as it leads to unnecessary repetition (especially if we wanted to add more currency units!). Instead, hint at the approach shown above: convert everything via a common unit, requiring only two conversions.

Question 5: Below is a solution to this exercise:

Demonstrator Notes: Some students may skip the note directing them to review tuples in the intermediate Week 1 material. Before offering help, check that they understand what a tuple is. If they do not, redirect them back to that material.

Advanced: Conditional Expressions and Lazy Evaluation

Question 1: An answer to this question is given below:

Demonstrator Notes: The logic in this question is very similar to the absolute value example in the Conditional Expressions section. If students are unsure what to do here, begin by referring them back to this example.

Question 2: The answers to this question, alongside commented code are given below:

Demonstrator Notes: Explanations of the behaviour are given below:

  • The first statement gives a division by zero error because the left-hand side is True, so Python must also evaluate the right-hand side to determine the result of the and.

  • The second statement does not throw an error: since the left-hand side is False, Python stops there and assigns False directly to my_variable without checking the right-hand side.

  • The third statement avoids the error for the same reason as the second. Wrapping the code in str() means my_variable is assigned the string value "False" instead of the boolean value False.

  • The fourth case again causes a division by zero error. This is because str(False) is the string "False", which is a truthy value in Python (the only Falsy string is the empty string ""). Since it is not False, Python must evaluate the second argument 1/0, which triggers the error.

Question 3: When Python evaluates an and expression, it checks the left-hand side first.

  • If my_boolean is True, the right-hand side (print(...)) must also be evaluated, so the message is printed.

  • If my_boolean is False, Python stops immediately, as it knows the and must be False, and the right-hand side is never run - so nothing is printed.

Demonstrator Notes: If students are struggling with this question, first refer them to the text in the Lazy Evaluation section. This section offers a similar explanation to the above text.

Question 4: An answer to this question is given below:

Demonstrator Notes: This question may be challenging for students who are still new to Boolean logic. Encourage them to first rewrite the statements in plain English before attempting to code, drawing clear links between the and, or, and not operators and their plain-English meanings.

Question 5: The rule for evaluating x or y is:

  • If x is Truthy, return x.
  • If x is Falsy, return y.

This is the mirror image of how and works. Some example code is given by:

Demonstrator Notes: The reasoning behind the answer is as follows. Suppose x and y are Boolean values and we want to evaluate x or y. We would do the following

  • First check x. If x is True, then the whole or expression is True and there is no need to check y. In this case, we return x.

  • If x is False, then we must check y. If y is True, the whole expression is True; otherwise, it is False. In either case, the result is the truth value of y, so we return y.

Generalising from Booleans, we replace True with Truthy and False with Falsy, giving the final rule:

  • If x is Truthy, return x.
  • If x is Falsy, return y.