The following exercises provide additional practice problems (not to turn in) for our material this week. Try to solve each problem on paper / whiteboard first before using Thonny to confirm your answers. You are encouraged to work on these practice exercises with classmates throughout the week.
Each of the following loops is an attempt to sum up the numbers from 1 to n,
e.g.1+2+ ... +n
(you can assume n
is initialized to some value). For
each case, explain why the code doesn’t actually sum the numbers 1 through n.
a.
sum = 0
for i in range(n):
sum = sum + i
b.
sum = 0
for i in range(n):
temp = sum + (i+1)
sum = temp
c.
sum = 0
for i in range(n):
sum = (i+1)
d.
sum = 0
for i in range(n):
temp = (i+1)
sum = temp
Write a function named factorial
that has a single parameter, an integer
n
, and returns n!, i.e. 1*2*3* ... n
.
def mystery():
for i in range(5):
print(2 + 2*i)
rand_time
that returns a random valid time in HH:MM
format as a string. The result can have only a single hour digit, i.e.
1:01
and 10:15
are valid results, but must have two minutes digits,
i.e. 1:1
is not a valid result. As a trickier extension, adapt your
function to always generate two hour digits, i.e. 1:01 should be represented
as 01:01
.