Practice Problems 2 Complete before class on 2021-09-24

Complete the following problems on paper. Try to solve each problem on paper first before using Thonny to confirm your answers.

  1. 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
    
  2. Would the following code execute without an error? If so, what would it print?

     for i in range(0):
         print("In the loop")
     print("After the loop")
    
  3. Write a function named factorial that has a single parameter, an integer n, and returns n!, i.e. 1*2*3* ... n.

  4. Write a docstring for the following function
     def mystery():
         for i in range(5):
             print(2 + 2*i)
    
  5. Write a function named 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.

  6. Write a function dice_pair that returns the sum of “rolling” two six sided dice, i.e., simulate rolling to two dice and return the sum of the rolled numbers.