it’s a weekend and my professor isn’t answering emails, we went over break statements in class and I was sure I understood it, but I keep getting questions like this wrong (it wants you to show the output):
stop = int(input()) result = 0 for a in range(3): for b in range(4): result += a + b print(result) if result > stop: break
I put this into Pycharm with the input ’17’ (I had tried so many attempts before to get the answer on my own, but zybooks gives you randomized problems in their challenge activities, and it wasn’t giving an explanation that was helpful) because I wanted to try and reverse engineer why the solution was the way it was, the output is:
first of all, I’m not sure why after it breaks it outputs the last number, since there’s no print statement for the outer ‘for’ loop. If I ignore that, the output I’m coming out with is:
I even wrote out how I think the RAM is storing these values and changing them (my professor said this was a good idea to do if you are having trouble since it helps step through the process the computer takes. Included below is a link to the picture of that, I’m sorry if it doesn’t make sense. https://imgur.com/a/t5o24Mo
I’m not trying to cheat, this homework is due Sunday, I would email my professor if I could to ask for help.
I tried to manually go through each iteration and figure out what each variable was and how it changed each iteration. I’m getting the first 2 iterations of the outer loop correct, but the break statement is where I’m having a problem.
If you’re not sure why the code is doing something, one easy way to help you figure it out is to just add more print statements, so you can see the variables at every step of execution.
Something like this:
for a in range(3): print("At the top of a range loop, a is:", a) for b in range(4): print("At the top of b range loop, b is:", b) print("a+b is:", a+b) print("Before adding, result is:", result) result += a + b print("After adding, result is now:", result) if result > stop: print("result", result, "is bigger than stop", stop, "so we will break the loop") break else: print("result", result, "is not bigger than stop", stop, "so the loop will keep going")