CSci 157 Homework #2

Due: February 07, 2025

For full credit:

Weekly assignments are grade out of 50 points. Unless specified otherwise, all homework assignments are to be done individually.

Reading. Zelle, Chapter 3

Part 1.  The print function (6+4 points)

Try each of these examples in the Python shell and record the results you get.

  1. We know we can assign a value to a variable and print the variable, as in:
    >>> n = 9
    >>>
    print(n)
    What happens if you try to do it all at once?
    >>> print(n = 9)
    
  2. How about this?
    >>> print(n + 5)
    
  3. Or this?
    >>> print("this" + "or" + "that")
  4. After trying these, consider what might be a general rule for what can be passed as an argument to print and write it out. Think in terms of statements versus expressions.

Part 2.  Evaluating Expressions I (16 points)

For each of the following, make a table showing predicted and actual results of expressions. First, evaluate the expression by hand and write down your predicted value, then evaluate the expression in the Python shell and record the actual value next to your prediction. If the expression will fail for some reason, say why (2 points each).
  1. 4 + 3 * 8 / 2 - 3
  2. (4 + 3) * 8 / 2 - 3
  3. 4 + (3 * 8) / (2 - 3)
     
  4. 4 + (3 * 8) % 5
  5. 'cost: ' + '80 - 30'
  6. "cost: " + 80 - 30
  7. 'price: ' + str(80 + - 30)
  8. 'Inventory: ' + str(17) + " units."

Part 3.  Evaluating  Expressions II (10 points)

For this section, recall how we used the type() function to determine a value's type in Python.

Evaluate each expression assuming these assignments: x = 15, y = 2, z = -2, and p = 1.5.  Record the result and type of the resulting value.
You'll need to import math before trying  #4.

  1. x / z
  2. x // z
  3. x / (z - y + 1) 
  4. x * math.pow(p,2) + y * p + z
  5. "Number = " + str(x) + " Total cost =  " + str(x * y)

Part 4.  Evaluating for loops (14 points) 

A previously assigned reading included examples of definite loops, described in Zelle, Section 2.6. These questions explore the workings of these statements.

Turning in Your Work. You can turn in written exercises one of these ways: