Whenever my students are having difficulty with debugging their code, I always tell them, “play computer.” In other words, pretend you are the computer, and follow your instructions exactly as you have written them.
For your program, when you press the A button, this code runs:

So, the only thing that happens is the variable knappA is changed to on. We can make keep track of that in a table of variables:
variable |
value |
antallPoeng |
0 |
knappA |
on |
knappB |
off |
So, when pressing the A button, nothing in the code changes the score.
Now, let’s see what happens when the B button is pressed:

The first thing that happens is the knappB
variable is set to on
. Let’s make a note of that in our table:
variable |
value |
antallPoeng |
0 |
knappA |
on |
knappB |
on |
Then, we reach the if
statement. If knappA
is on
and knappB
is on
, then we run the code in the upper block. If not, then we run the code in the lower block. From our table above, we see that both knappA
and knappB
are on
. So, the upper block runs. In that upper block, we add 1
to andtallPoeng
, and we set knappA
and knappB
to off
. Let’s update our table:
variable |
value |
antallPoeng |
1 |
knappA |
off |
knappB |
off |
Now, you try it. What happens if you press the B button a second time? According to your code, when does the score change?
Click on the spoiler below to see my answers.
Answers
According to your code, the only time that the score changes is when you press button A first, and then press button B. Every time you press the B button, the values for knappA
and knappB
are reset to off
.
Note that the following code does the same thing while using fewer blocks:
