Practice Problems 1 Complete before class on 2021-09-17

Try to solve each of these problem on paper first before using Thonny to confirm your answers.

  1. [PP Problem 2.1] Indicate whether the result is an int or float by (not) including a decimal point, e.g. 5 for an int, 5.0 for a float.

    For each of the following expressions, what value will the expression evaluate to? The new operator we didn’t see in class is %, called modulus, which evaluates to the remainder of its left operand divided by its right operand.

    a. 9 - 3
    b. 8 * 2.5
    c. 9 / 2
    d. 9 / -2
    e. 9 // 2
    f. 9 % 2
    g. 9.0 % 2
    h. 9 % 2.0
    k. 9 // -2.0
    l. 4 + 3 * 5
    m. (4 + 3) * 5
    n. (7 // 2) * 2 + 7 % 2

  2. [PP Problem 4.5] Given variables x and y, which are assigned the values 3 and 12.5, respectively, use the print function to print the following messages (the print prints its input or arguments to the screen) by constructing the appropriate string. When numbers appear in the messages, variables x and y should be used instead.

    a. The rabbit is 3.
    b. The rabbit is 3 years old.
    c. 12.5 is average.
    d. 12.5 * 3
    e. 12.5 * 3 is 37.5.

  3. If we execute the following code, what will the final value be for the variable z? # indicates a comment, everything on the line including and after the # is ignored by Python (is not executed).

    i = 7
    a = i
    i - 1
    z = i * a
    # z = 2
    z + a
    
  4. The program below is supposed to calculate the length of the hypotenuse of a right triangle with sides 3 and 4 and print out the answer. However, the program has three errors in it: one syntax error, one logic error and one runtime error relating to type. What are the three errors? Try to figure it out without running the program. Think Python describes these three different types of errors (note they call “logic errors” “semantic errors”).

    # Take the sqrt of a number
    def my_sqrt(x):
        return x ** (1//2)
       
    # Calculate the length of the hypotenuse of a right triangle
    def hypotenuse_length(a, b)
        sum = a**2 + b**2
        return my_sqrt(sum)
       
    print("If a is 3 and b is 4 then hypotenuse is " + hypotenuse_length(3,4))
    
  5. Write a function named x_intercept that has two parameters, the slope and intercept of a line, and returns the x intercept (i.e. the value of x where y=0).