CSci 157 Homework #2
Due: February 07, 2025For full credit:
- Written problems are due by class time on the due date
- See the Turning in Your Work section below
Weekly assignments are grade out of 50 points. Unless specified
otherwise, all homework assignments are to be done individually.
Part 1. The print function (6+4 points)
Try each of these examples in the Python shell and record the results you get.
- We know we can assign a value to a variable and print the variable,
as in:
>>> n = 9
What happens if you try to do it all at once?
>>> print(n)>>> print(n = 9)
- How about this?
>>> print(n + 5)
- Or this?
>>> print("this" + "or" + "that")
- 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).- 4 + 3 * 8 / 2 - 3
-
(4 + 3) * 8 / 2 - 3
- 4 + (3 * 8) / (2 - 3)
- 4 + (3 * 8) % 5
-
'cost: ' + '80 - 30'
-
"cost: " + 80 - 30
-
'price: ' + str(80 + - 30)
-
'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.
-
x / z
-
x // z
-
x / (z - y + 1)
-
x * math.pow(p,2) + y * p + z
-
"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.
- (4 points) Which of these two for statements run
without error? For the one that works, determine the type of
the variable
x
used.
- (4 points) What is output by each of the for statements
below? Give your best guess as to why this is.
- (6 points) Technically, any sequence will work as
the range of a for statement. As it turns out, a Python string
is also a sequence. Show what happens when this loop is run:
Now show how to rewrite this code so that the output looks like this:
Turning in Your Work. You can turn in written exercises one of these ways:
- Complete the assignment on paper and turn in at the beginning of class on the due date
- Complete the assignment in a text editor and post to the Assignments page on BrightSpace by the due date
- In either case, make sure your name is clearly visible. All homework is to be pledged.