简体   繁体   中英

How do break and continue loops work in python?

input: 17

  stop = int(input())
    result = 0
    for a in range(5):
        for b in range(3):
            result += a + b
        print(result)
        if result > stop:
            break

Can someone please explain to me how this code yields: 3 9 18

I just can't seem to wrap my head around how those numbers are computed... any help is appreciated!

The best I can explain is like this:

stop = int(input("Input a stop value:"))
print(f"stop value is: {stop}")
result = 0
for a in range(5):
    for b in range(3):
        print(f"adding: a{a} + b{b}")
        result += a + b
        print(f"result is now: {result}")
    if result > stop:
        print(f"result {result} is superior to {stop}, break")
        break

print(f"\nFinal result is {result}")

Input a stop value: 17
stop value is: 17
adding: a0 + b0
result is now: 0
adding: a0 + b1
result is now: 1
adding: a0 + b2
result is now: 3
adding: a1 + b0
result is now: 4
adding: a1 + b1
result is now: 6
adding: a1 + b2
result is now: 9
adding: a2 + b0
result is now: 11
adding: a2 + b1
result is now: 14
adding: a2 + b2
result is now: 18
result 18 is superior to 17, break

Final result is 18

Demo

The inner loop adds a 3 times to result and all values of b (0, 1, and 2). This means that every time the loop runs, result += 3*a + 3. Then, the outer loop prints this value. At 0 initially, after the first increment with a=0, this is 3 (adds 3*0+3) after the second increment 9 (adds 3*1+3=6) and the third 18 (adds 3*2+3=9). Each round it also checks if the result is larger than the value at which to stop and calls the break keyword. In Python, this ends the execution of a loop immediately, so the program exits the outer loop and completes the program. continue , as you asked about in the title skips the remaining code in the loop after the statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM