The why of using break

Asked

Viewed 138 times

0

I wanted to know why the use of break in code(I realized that without break, the code is flawed):

lista = list()
pos = 0
for c in range(0, 5):
    n = int(input('Digite um valor: '))
    if c == 0 or n > lista[-1]:
        lista.append(n)
    else:
        while pos < lista[pos]:
            if n < lista[pos]:
                lista.insert(pos, n)
                break
            pos += 1
print(lista)

It is a code that puts the numbers in order in a list without the use of "Sort()"

3 answers

5


The break ends the running repeat loop and continues on the next instruction after this repeat loop, either a loop designated by while or for. In your case, the break is finishing the loop while pos < lista[pos]: and resuming the execution in for c in range(0, 5):.

inserir a descrição da imagem aqui

2

The break serves to exit the loop it is in. For example, note the code below

n = 0
while n < 5:
    print(n)
    n += 1

print('Fim do Loop!)

If you run this code, it will appear on the screen

0
1
2
3
4
Fim do Loop!

but if you add a break like

n = 0
while n < 5:
    if n == 3:
        break
    print(n)
    n += 1

print('Fim do Loop!)

then what will appear on the screen will be

0
1
2
Fim do Loop!

because, when n==3, activated the break, and exited the while

1

The statement break serves to interrupt the execution of a repeat loop (while and for), no more code below it being executed that is within the repeat structure.

See below for an example:

for numero in range(5):

    if numero > 2:
        break

    print(numero)

See online: https://repl.it/repls/FruitfulDigitalPatterns

In the above code, only the numbers 0, 1 and 2 will be printed because the break interrupts the replay without caring about the rest of the code. That’s exactly why Python doesn’t allow you to write code below and in the same block as it, since that wouldn’t make any sense.

This statement is also very similar to statement continue, which is another instruction in which it ignores the code below it, but continues the execution of the repeating structure.

for n in range(1000):

    if n > 10: 
        break     # Sai do for loop

    if n % 2 == 0: 
        continue  # Volta para o início do for loop

    print(n)

See online: https://repl.it/repls/TediousTriflingAddons

Both the break as to the continue are present in many programming languages such as Python, Java, Javascript, Ruby, etc., having the same function within repetition structures.

  • But then break wouldn’t skip pos += 1 in my code?

  • Would not, the statement break pula that line of code and everything below it that is in the same repeat block when running inside your block if.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.