Note: Click on "Kernel" > "Restart Kernel and Run All" in JupyterLab after finishing the exercises to ensure that your solution runs top to bottom without any errors. If you cannot run this file on your machine, you may want to open it in the cloud .
The exercises below assume that you have read the first part of Chapter 1.
The ...
's in the code cells indicate where you need to fill in code snippets. The number of ...
's within a code cell give you a rough idea of how many lines of code are needed to solve the task. You should not need to create any additional code cells for your final solution. However, you may want to use temporary code cells to try out some ideas.
for
-loops¶for
-loops are extremely versatile in Python. That is different from many other programming languages.
As shown in the first example in Chapter 1 , we can create a
list
like numbers
and loop over the numbers in it on a one-by-one basis.
numbers = [7, 11, 8, 5, 3, 12, 2, 6, 9, 10, 1, 4]
Q1: Fill in the condition of the if
statement such that only numbers divisible by 3
are printed! Adjust the call of the print() function such that the
for
-loop prints out all the numbers on one line of output!
for number in numbers:
if ...:
print(...)
Instead of looping over an existing object referenced by a variable like numbers
, we may also create a new object within the for
statement and loop over it directly. For example, below we write out the list
object as a literal.
Generically, the objects contained in a list
objects are referred to as its elements. We reflect that in the name of the target variable element
that is assigned a different number in every iteration of the for
-loop. While we could use any syntactically valid name, it is best to choose one that makes sense in the context (e.g., number
in numbers
).
Q2: Fill in the condition of the if
statement such that only numbers consisting of one digit are printed out! As before, print out all the numbers on one line of output!
for element in [7, 11, 8, 5, 3, 12, 2, 6, 9, 10, 1, 4]:
if ...:
print(...)
An easy way to loop over a list
object in a sorted manner, is to wrap it with the built-in sorted() function.
Q3: Fill in the condition of the if
statement such that only odd numbers are printed out! Put all the numbers on one line of output!
for number in sorted(numbers):
if ...:
print(...)
Whenever we want to loop over numbers representing a series in the mathematical sense (i.e., a rule to calculate the next number from its predecessor), we may be able to use the range()
built-in.
For example, to loop over the whole numbers from 0
to 9
(both including) in order, we could write them out in a list
like below.
Q4: Fill in the call to the print() function such that all the numbers are printed on one line ouf output!
for number in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
print(...)
for number in range(...):
print(...)
for number in range(...):
print(...)
for number in range(...):
print(...)