Can Computers Think?
(CSC 106) Checking your understanding
Questions:
The fragment of code below is supposed to print "One" if the variable a equals 1, "Two" if a equals 2,
"Three" if a equals 3, and "Other" if a is something else. Instead it prints "One" and "Other" if a
equals 1, "Two" and "Other" if a equals 2, "Three" if a equals 3, and "Other" if a is something else.
if a == 1:
print("One")
if a == 2:
print("Two")
if a == 3:
print("Three")
else:
print("Other")
1. Explain what is going wrong.
Because each of the if conditionals are checked independently of
each other, "Other" will print for all values that aren’t
exactly 3. ....................................................
2. How can it be fixed?
Change "if a==2" and "if a==3" into elifs. ....................
...............................................................
...............................................................
1
Consider the following code snippets. For each of them, what is Reeborg going to do when this code is
run? You can assume that Reeborg is carrying an unlimited supply of tokens and is starting in the bottom
left corner facing East as usual.
Use the world images below to sketch the behavior of Reeborg for each of the two code snippets, and
explain why Reeborg is behaving this way.
while front_is_clear(): while front_is_clear():
put() put()
move() move()
(a) (b)
The first code snippet directs Reeborg to walk forward, putting down
something (this example uses tokens) with every step it takes until it
reaches a wall. As a result, we get a line of tokens going up to the
next to last square, while Reeborg will end facing the wall.
The second code snippet is an infinite loop whenever Reeborg isn’t
standing in front of a wall. As written, Reeborg will continue placing
objects at its location until the space in front of it is no longer
clear, but since walls don’t move, this condition will never change
since the loop doesn’t tell Reeborg to move. .......................