Midterm Review: Python Problem Sets 3

  1. Is there a difference between these two lines of code? Would they result in an runtime error?

    x = (a = 5)
    
    x = a = 5
    

     

  2. What is the value of a after the second assignment?

    >>> print(a := 10)
    >>> a = 20
    >>> print(a := a + 5)
    

     

  3. What is the output of this code? Explain the difference between the two approaches. Any errors?

    # Approach 1
    print(a = 7)
    
    # Approach 2
    print(a := 7)
    

     

  4. Identify and fix the error in this code. Can you fix this by adding just one more character?

    while input_str = input("Enter text: "):
        print(input_str)
    

     

  5. Explain the difference between the // operator and int for division truncation.

    >>> 2.9 // 1
    >>> int(2.9 / 1)
    >>> -2.9 // 1
    >>> int(-2.9 / 1)
    

     

  6. What will be the type and value of each result?

    a = 5 / 2
    b = 5 // 2
    c = int(5 / 2)
    

     

  7. What are the results of rounding these numbers? Why?

    >>> round(1.7)
    >>> round(2.5)
    >>> round(1.5)
    >>> round(2.6)
    

     

  8. Explain the output of these expressions:

    print(bool('False'))
    print(bool(''))
    print(bool(0.0))
    print(bool([]))
    

     

  9. What will the output be?

    print("{} {} {}".format("seven", "eight", "nine"))
    

     

  10. What will the output be?

    print("{0} is the first, {1} is the second, and {0} is the first again".format("one", "two"))
    

     

  11. What will the output be?

    print("{0}, {val1}, and {1}.".format("the penguin borrowed a ladder", "the kangaroo came by for a smoke", val1="the otter mugged me"))
    

     

  12. What will the output be?

    print("{1} {0} {val1}".format("the penguin borrowed a ladder", "the kangaroo came by for a smoke", val1="the otter mugged me"))