Loops - Solutions
This notebook contains the solutions to the week 3 Beginner, Intermediate and Advanced exercises.
Table of Contents
Beginner: For and While Loops
Question 1: The below code box contains an answer to this question.
Demonstrator Notes: The aim of this question is to give students some practice thinking about
whileloops, and in particular, when they should terminate. If students are struggling, emphasize the fact that, if we were doing this task by hand, we would look at the words one by one, and that we only stop writing when there are no more words left. Try to get the students to translate this natural language into code.
Question 2: A solution is given below.
Demonstrator Notes: The aim of this question is to encourage students to form a habit of looking up documentation for themselves. Please do not give them the answer straight away, but instead encourage them to look up online resources.
Question 3: The below code computes the factorial with a while loop.
Demonstrator Notes: Like Question 1, this question aims to get students thinking about
whileloops and when they should terminate. If the students are struggling, have them perform the computation by hand on paper. They will likely compute \(6 \times 5\) first, then multiply that by \(4\) and so on, stopping only when they hit \(1\). Try to relate the steps they perform to the process of coding thewhileloop.
Question 4: An answer to this question is given below:
Demonstrator Notes: This question aims to give students practice combining conditional logic with loops. For many students, this may also be the first time they are encountering the idea of appending value to a list inside each iteration of a
forloop. A common error in this question isAttributeError: 'NoneType' object has no attribute 'append'. If you see this error, the chances are the student has writtenoutput_list = output_list.append(i**2)when they should just haveoutput_list.append(i**2). Theappendfunction does not return anything, it just adds the element to the list, so writingoutput_list = ...just setsoutput_listtoNone.
Question 5: The code will print "Python" four times, one for each power of two.
Demonstrator Notes: Encourage students to write this one out on paper if they are stuck. Again, this question is mainly for practice so try to avoid giving them the answer directly where possible.
Question 6: The problem here is that the position = position + 1 is incorrectly indented and thus the position only changes when we encounter vowels. Once we encounter a consonant, we get stuck at that position indefinitely, never updating. The solution is as follows:
Demonstrator Notes: The aim of this question is to give students practice debugging code. Encourage them to use the
whileloop.
Question 7: An example answer is given below.
Demonstrator Notes: The correct output for this question is:
Difference between highest and lowest scores: 61 Highest score: Ava Brooks with 99 Lowest score: Noah Murphy with 38This is the first time students have been asked to compute a maximum/minimum using loops. If students are struggling with this, simplify the problem and ask them to work out only the maximum of a singlelistusing aforloop, working through the solution with them on paper first if you need to.
Question 8: A solution to this question is given below:
Demonstrator Notes: This question is tough, so reassure students if they are struggling with it. Also, be aware that many students may not have studied Pascal’s triangl and be unaware of it’s construction. Make sure the student understands the context of the question (i.e. what Pascal’s triangle actually is), before offering to help them solve it.
Question 9: One possible solution is provided below:
Demonstrator Notes: A common stumbling point is that students don’t realize they must convert the integer to a string to reverse its digits. To help them see this, suggest working through a simple example like
n=102(ignoring the loop for now): guide them step-by-step on converting to a string, reversing it, and checking if it’s a palindrome.
Question 10: Here is an example solution.
Demonstrator Notes: The expected solution is \(840\). If a student is struggling, provide them with a candidate number (e.g.
candidate=480) and have them write some code to check whether thiscandidateis divisibly by \(1,...,8\). Then ask them how they might expand on this code by looping over all possible candidates.
Intermediate: Advanced Iteration
Question 1: Here is the solution:
Demonstrator Notes: This question is fairly straightforward and just involves using the
zipfunction. If students need help on this question, advise them to read over the section onenumerateandzip. If they are still struggling, advise them to drop a level and attempt the beginner notebook.
Question 2: Below is a solution for this question.
Demonstrator Notes: Many students may still be fairly new to the idea of an
index, so it is worth checking they understand the question correctly before helping with the code on this question. It is also expected that many will forget that Python is zero-indexed, but will not voice their confusion. Make sure they understand which index corresponds to which element in the list. The expected output for this question is:
[0, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, 19]
Question 3: The answer to this question is to change the break to a continue. This is as the break ends the loop prematurely, whilst continue just skips to the next iteration. The current code gets to num=1 and then executes the break statement, thus terminating the loop early.
Demonstrator Notes: Encourage students who are struggling to consider what the
breakstatement is doing in this code. If necessary, advise them to revisit thebreak,continueandpasssection. The hope is that this will prompt them to consider the differences between these keywords.
Question 4: Solution code is provided below:
Demonstrator Notes: This question is drawing on several concepts and is technically challenging. It is expected that some students will have forgotten how to
appendto a list. If a student is struggling with this, prompt them to attempt question 4 from the beginner notebook as a warmup for this question. This should hopefully encourage them to think about building collections one item at a time usingappend.
Question 5: The error in this code is the indentation of the else block. Here else should be at the same level as the if to make an if... else. However, it is at the level of the for creating a for...else. This means that it will always be executed for the last day so long as a break is not encountered in the loop. To rectify this, we just indent like so:
Demonstrator Notes: Encourage students who are struggling with this to revisit the
forandelsesection.
Advanced: Comprehensions
Question 1: The solution is below:
Demonstrator Notes: This question is reasonably straightforward and designed to give students practice with the syntax of comprehensions. If, even with help, a student is really struggling with this, suggest that they drop a difficulty level and look at the intermediate material.
Question 2: The answer to this question is as follows:
Demonstrator Notes: The “trick” to this question is to convert the integer to a string and loop over the characters of the string. A student who doesn’t spot this immediately is unlikely to realise this is how to solve the problem later. So, for this question, it is fine to give them a guided solution rather than trying to give prompts.
Question 3: Below is list comprehension for this question.
Demonstrator Notes: This question is challenging and it is expected that many students will struggle with the inner list comprehension. If a student is struggling, focus on a single value of
nand talk them through how you might check thatnis pluriperfect.
Question 4: The solution is given below:
Demonstrator Notes: The main objective of this question is for students to recognise that the set comprehension is the most appropriate choice when you need to list unique values. If they are using some other form of comprehension, please prompt them to reconsider this decision.
Question 5: The correct answer to this question is to use a generator comprehension, so that the values inside the comprehension are computed lazily (only when needed). If we use a list comprehension for this task, we will end up trying to compute 10000000000 values instantly and crash the memory.
Demonstrator Notes: The actual code for this answer would be very slow, as it is performing a very large computation. This is why the students have been told not to implement any code. However, the equivalent computation, when performed with a list comprehension, would consume too much memory and could crash the notebook entirely, so the generator comprehension is still preferable. If the students ask, tell them that we will cover more efficient tools for this task later in the course when we look at
numpy.