How to use a Python Break?

Asked

Viewed 3,058 times

0

Good afternoon, I am doing a job for the college on conversion, I have this code below and I wanted to use a break in it so when the user type a number q not be the '1' or '0' he of a msg and return so that the user type right, more not getting, can help me out ?

vet = []
soma = 0
potencia = 3
for i in range(4):
     ver = int(input('Digite UM numero entre 0 e 1: '))
     if ver => 2:
          print('Digite corretamente')
          break
     else:
         vet.append(ver)
         soma = soma + (vet[i] * (2 ** potencia))
         potencia = potencia - 1
print('Codigo binario convertido em decimal é: ', binDec())

  • what is the error? apparently the code is ok

  • when it passes to Else, it gets an infinite loop, rather than calling input only 4 times as requested !

  • There are syntax errors in your code that prevent you from testing the reported problem: if ver => 2, the operator => does not exist in Python (maybe wanted to use >=) and the function binDec used in the last line is not defined.

2 answers

2

You reversed the signals of the condition, you typed => when actually it is >=, also I think that the break would not be correct because it would stop the loop, but the continue that just interrupts the current cycle, and you could change this for range while, that way:

vet = []
soma = 0
potencia = 3

i = 0

while(i < 4):
  ver = int(input('Digite UM numero entre 0 e 1: '))

  if ver >= 2:
    print('Digite corretamente')
    continue
  else:
    vet.append(ver)
    soma = soma + (vet[i] * (2 ** potencia))
    potencia = potencia - 1  
  i += 1

print('Codigo binario convertido em decimal é: ', binDec())

This algorithm will run endlessly until you get the four entries correctly.

2


You can put continue in place of break.

vet = []
soma = 0
potencia = 3
for i in range(4):
 ver = int(input('Digite UM numero entre 0 e 1: '))
 if ver >= 2:
      print('Digite corretamente')
      continue
 else:
     vet.append(ver)
     soma = soma + (vet[i] * (2 ** potencia))
     potencia = potencia - 1
 print('Codigo binario convertido em decimal é: ', binDec())

This will cause the for loop to continue running even if it fails until the end of its execution, in case, its condition of range(4).

Browser other questions tagged

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