Researchers have found that some students hold the following misconception: if
statements "wait" for their conditional statement to become true. When that happens (at whichever point in the program), the corresponding block of code is executed.
For instance, consider this program:
size = 0
if size == 5:
print("Hello")
for i in [1, 2, 3, 4, 5]:
size = size + 1
print(size)
If a student understands this correctly, she would say that since size
is not equal to 5 when the if
statement is evaluated, "Hello" is never printed. The program proceeds to execute the for
loop and never returns to the if
statement to evaluate that again.
A student who holds the above misconception, however, would say that after size
becomes 5 at the end of the loop, the if
statement (which had been "waiting" all this time) would see that its condition would now evaluate to true. "Hello" would then be printed.
In this case, the student fails to see that each line of the program is executed in sequence, one line at a time. Instead, she views all lines of the program as being active all at once, monitoring the status of the variables constantly.
This misconception might also appear in students' understanding of the while
loop: the loop body is executed whenever its condition becomes true.
size = 10
while size < 5:
size = size + 1
size = 0
In the above example, the student might predict that the while
loop will execute as soon as size
is set to 0 at the end of the program.
A final variant of this misconception is believing that the while loop exits immediately after its condition becomes false. For instance:
size = 0
while size < 5:
size = size + 1
print(size)
size
becomes 5 at the last iteration of the loop, but before its value is printed. A student who held this misconception would predict that the output of this program would be as follows, leaving out the 5:
1
2
3
4
The correct behavior of while
loops is that its condition is only checked every after the loop body is executed completely.
To prevent this misconception, encourage students to trace through the examples line-by-line using CodeLens. This way, the students see the sequential flow of execution through the program.
Looks good!