2 Control flow
Exercise 2.1: Range
Type range(5) in the interpreter, what does the interpreter return? So what does for i in range(5)
mean?
Let’s also find out whether the interpreter can help us understand the object ‘range(5)’ better. Type
type(range(5)) in the interpreter. More on this soon!
range(5)就是创建一个从1到4的列表。for i in range(5)意味着创建一个循环,遍历range列表中的每一个元素。
Exercise 2.2: For loops
Use a for loop to:
(a) Print the numbers 0 to 100
(b) Print the numbers 0 to 100 that are divisible by 7
(c) Print the numbers 1 to 100 that are divisible by 5 but not by 3
(d) Print for each of the numbers x = 2; : : : 20, all numbers that divide x, excluding 1 and x. Hence,
for 18, it should print 2 3 6 9.
(a):
(b):
(c):
(d):
Exercise 2.3: Simple while loops
Instead of using a for loop, use a while loop to:
(a) Print the numbers 0 to 100
(b) Print the numbers 0 to 100 that are divisible by 7
(a):
(b):
'''
Exercise 2.5: While loops
Use a while loop to find the first 20 numbers that are divisible by 5, 7 and 11, and print them Hint:
store the number found so far in a variable.
Pseudo-code:
number found = 0
x = 11
while number found is less than 20:
if x is divisible by 5, 7 and 11:
print x
increase number found by 1
increase x by 1
'''
num_found = 0
x = 11
while num_found<20:
if(x %3==0 and x%5 == 0 and x%11 == 0):
print(x,end = ' ')
num_found = num_found +1
x = x +1
Exercise 2.6: More while loops
The smallest number that is divisible by 2, 3 and 4 is 12. Find the smallest number that is divisible by
all integers between 1 and 10.
'''
Exercise 2.7: Collatz sequence
A Collatz sequence is formed as follows: We start with some number x0, and we find the next number
in the sequence by
xi+1 = (x 3xi=i2 if + 1 if x xii is even is odd
If xi = 1, we stop iterating and have found the full sequence.
For example, if we start with x0 = 5, we obtain the sequence:
5 16 8 4 2 1
It is conjectured, though not proven, that every chain eventually ends at 1.
Print the Collatz sequence starting at x0 = 103
'''
x = 103
print(x,end = ' ')
while x != 1:
if(x%2 == 0):
x = int(x/2)
else:
x = x*3+1
print(x,end = ' ')