CS 107: Pictures and Sounds: Programming with Multimedia
Kalamazoo College
Spring 2008
Problem Set on If Statements and For Loops
- For what possible values of
x are statements A and B
executed
in the following two pieces of code?
- First piece of code:
if (x >= 3):
if (x == 7):
statement A
else:
statement B
- Second piece of code:
if (x >= 3):
if (x == 7):
statement A
else:
statement B
- Explain the difference between the following two pieces of code.
For each piece of code assume that the variables
x and
y have been
defined and assigned a value before reaching this section.
- First piece of code:
s = 0
if ( x > 0 ):
s = s + 1
if ( y > 0 ):
s = s + 1
- Second piece of code:
s = 0
if ( x > 0 ):
s = s + 1
elif ( y > 0 ):
s = s + 1
- What does the following
for statement do? Assume that
n
is some positive integer.
for b in range(n, 0, -1):
print b
- For the following loops, indicate what gets printed. (Note
that
str is a function that takes a number and returns
the corresponding string. For example str(3) returns
the string "3".)
- First piece of code:
for x in range(4):
for y in range(1, 4):
print str(x) + ", " + str(y)
- Second piece of code:
for x in range(4):
for y in range(x, 4):
print str(x) + ", " + str(y)