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
ifstatements. If a student is struggling, check in with them regularly and recap strings and thelen()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 Yearsection. 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.60934instead ofdistance_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 pythononline. 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 < 15andx > 30cases to get:
Next, note that the final
elifshould never be evaluated as ifz < -1thenz < 0, so theifis executed instead.
We can now combine the innermost
ifandelseas follows:
Now, note that the
z > 20can’t ever be evaluatedTrue, as if we are inside the outerifthenz < 0.
We can now combine the inner
ifandelif:
By combining the outer
ifand 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
matchstatement. 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
ifstatements, students may wonder what the point ofmatchis. Point them to the sectionConverting Long elif Statements to match, which provides a more compelling example and highlights the advantages ofmatchin 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 atupleis. 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 Expressionssection. 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 zeroerror because the left-hand side isTrue, so Python must also evaluate the right-hand side to determine the result of theand.The second statement does not throw an error: since the left-hand side is
False, Python stops there and assignsFalsedirectly tomy_variablewithout checking the right-hand side.The third statement avoids the error for the same reason as the second. Wrapping the code in
str()meansmy_variableis assigned the string value"False"instead of the boolean valueFalse.The fourth case again causes a
division by zero error. This is becausestr(False)is the string"False", which is a truthy value in Python (the onlyFalsystring is the empty string""). Since it is notFalse, Python must evaluate the second argument1/0, which triggers the error.
Question 3: When Python evaluates an and expression, it checks the left-hand side first.
If
my_booleanisTrue, the right-hand side (print(...)) must also be evaluated, so the message is printed.If
my_booleanisFalse, Python stops immediately, as it knows theandmust beFalse, 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 Evaluationsection. 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, andnotoperators and their plain-English meanings.
Question 5: The rule for evaluating x or y is:
- If
xisTruthy, returnx. - If
xisFalsy, returny.
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
xandyare Boolean values and we want to evaluatex or y. We would do the following
First check
x. IfxisTrue, then the wholeorexpression isTrueand there is no need to checky. In this case, we returnx.If
xisFalse, then we must checky. IfyisTrue, the whole expression isTrue; otherwise, it isFalse. In either case, the result is the truth value ofy, so we returny.Generalising from Booleans, we replace
TruewithTruthyandFalsewithFalsy, giving the final rule:
- If
xis Truthy, returnx.
- If
xis Falsy, returny.