I'm a beginner CS student learning Python right now. I have a very basic challenge on Zybooks that wants me to enter the output of the code provided. It's designed to help understand how break and continue statements work within for and while loops. I've tried to go through the logic of each line of code, and I just can't grasp it. If anybody can help me understand this more, I'd appreciate it.
stop = int(input()) result = 0 for n in range(10): result += n + 2 if result > stop: break print(n) print(result) 32 Answers
Using break will simply stop the loop and exit it, without continuing to iterate and execute the code.
Using continue will stop executing the block, will iterate and will work normaly from there
For example:
for i in range(10): print(i) if i > 5: break print(i) The code above will stop at i==6
Output will look like this:
>> 0 >> 0 >> 1 >> 1 >> 2 >> 2 >> 3 >> 3 >> 4 >> 4 >> 5 >> 5 for i in range(10): print(i) if i > 5: continue print(i) The code above will print i only for values from 0 to 5. But the code will be executed until that continue.
Output:
>> 0 >> 0 >> 1 >> 1 >> 2 >> 2 >> 3 >> 3 >> 4 >> 4 >> 5 >> 5 >> 6 >> 7 >> 8 >> 9 Hey OP I know it has been awhile since this was last posted and you may be through the course by now. The below is what we are not seeing in the Zybooks material. It would make more sense to see the debug running through each equation and changing the variables on each loop as you go.
Even after we learn the increment stuff, we aren't shown long form. So after bashing my head against it, this is how I worked my way through it.
Apologies on incrementation looking off. First time posting in this forum and first time using the code block in a forum.
stop = 5 result = 0 for n in range(10): result += n * 4 if result > stop: break print(n) print(result) #Loop 1 print N is 0 result is incremented by 0 0 += 0 * 4 == 0 So result is 0 and incremented by 0 or 0 + 0 == 0
#Loop 2 print N is 1 result Incremented by 4 0 += 1 * 4 == 4 So result is 0 incremented by 4 or 0 + 4 == 4
#Loop 3 print N is 2 result Incremented by 8 4 += 2 * 4 == 8 So result is 4 incremented by 8 or 4 + 8 == 12