Finish a loop when a given string is typed

Asked

Viewed 280 times

1

I’m trying to fill a list with numbers, so I made a loop:

lista=[]
i = float(input())
lista.append(i)

while (i != '.'):
    i = float(input())
    lista.append(i)

However I wanted that when putting the string ".", the loop ended, so that the point did not appear in the list.

3 answers

4


Instead of calling input twice (one out of the while and another inside), do it once:

lista = []
while True:
    i = input('Digite um número (ou "." para encerrar): ')
    if i == '.':
        break # sai do while
    try: # tenta converter para float
        lista.append(float(i))
    except ValueError: # se deu erro na conversão, mostra mensagem de erro
        print('Você não digitou um número válido')

print(lista)

while True is a loop "infinite", which is only interrupted by break - and I just call the break if typed ., which is the exit condition. So you avoid having to call input twice (if the message needs to be changed, for example, you only need to change in one place - do not repeat things unnecessarily)

If not typed a dot, I try to convert to number and add to list.

If a valid number has not been entered, I capture the ValueError and show an error message (and in that case, the number is not added in the list).

Notice that unlike what you did to another answer, don’t need to use str(input()), for input already returns a string, then use str here is redundant and unnecessary.

And use isnumeric hides some traps: there are several characters for which isnumeric returns True but error when converting to float, see here. You’d better wear it soon float and capture the ValueError to know if a number has not been entered.

2

You have defined the variable i as float (automatically the value passed has to be float, can’t be string or boolean), the . is a string, and when the user tries to pass this string instead of the float the python generates the value error (Valueerror)

The code would look like this:

lista=[]
i = str(input('Digite um número: ("." para parar):'))
if i.isnumeric() == True: # Verifica se o valor passado é um número
    lista.append(float(i)) # Adiciona o float do número a lista

while (i != '.'):
    i = str(input('Digite um número: ("." para parar):'))
    if i.isnumeric() == True:
        lista.append(float(i))

And in the pythonic way, more correct and visually beautiful so:

lista = [] # Define a lista

while True: # Entra em loop infinito
    i = str(input('Digite um número: ("." para parar):')).strip() # Capta o que o usuário digitar e no fim remove os espaços em branco (se tiver)
    if i == '.': # Verifica se o valor passado é a condição de parada, se sim ele para
        break
    else:
        if i.isnumeric() == True: # Verifica se o valor passado é um número
            lista.append(float(i)) # Adiciona o float do número a lista

I hope it helped, good studies!

  • our thank you very much, that’s exactly what I was needing, I didn’t know the use of isnumeric so I wasn’t getting.

  • There are other ways to detect whether the value passed is a number or not, but the most viable to date is the . isnumeric(), there are many things in python that make our work easier, and this is one of them haha

  • 2

    @Paulo Thiago, the input that captures the value of the variable i does not need the function str. Because, the input already passes the entered value as string. In this case, the function str becomes redundant. Hug.

  • 2

    @Jedinegão Just one detail: there are several characters for which isnumeric returns True but error when converting to float, see here. You’d better wear it soon float and capture the ValueError to know if a number has not been entered (as I did in my answer)

  • 1

    @Solkarped I used the str(input()) just to clarify and make it clear to @Jedi Black Guy, but overall it’s less redundant to just use the input(), as you said yourself. Hug

  • @hkotsubo For this situation the .isnumeric() served well, but it’s like you said, there are several values that he ends up returning True, so your answer turns out to be also very viable

  • 1

    @Paulothiago It will only serve well if the user does not type any of these problematic characters I mentioned. All right that are not very common characters in our day-to-day, but if you are reading user entries, you better be prepared to receive "anything" :-)

Show 2 more comments

1

They actually had some really good, useful and functional responses so I’m just going to say some things again that are the same as others

1 - If you set the input to float, you cannot receive a string because when the message is received, it will be converted, but it would be wrong to try to convert ".". The best solution would be to check if it is a number later

2 - You could have simply put as an infinite loop to be able to decrease the program size, but it is not required

3 - I don’t know if this is from your IDE, but keep an eye out because in python it is not used () when it will give a condition "while (i!='.'):" this in python does not happen

No more bullshit, I’ll show you how my solution turned out:

Only broken value

lista=[]
while True:
   i = input('Digite um número (ou "." para encerrar): ').replace(',','.')
   """Aquele replace caso tenha uma , ele irá substituir por . para poder converter 
      para float"""
   if i[0].isnumeric() and '.' in i:
      #Aqui especificamos que para poder ser adicionado é apenas um número quebrado
      #Se digitar um inteiro não será adicionado
      #O .isnumeric vai verificar se a primeira palavra (i[0]) é um número
      i = float(i)
      lista.append(i)
   else:
      if i=='.':
         print(lista)
         exit('Obrigado por usar o programa!')
         #uma forma mais rápida de sair do programa sem usar print
      else:
         print('Por favor digite algo válido')

Any number

lista=[]
while True:
   i = input('Digite um número (ou "." para encerrar): ').replace(',','.')
   if i[0].isnumeric():
      #Mas para ser adicionado ainda é necessário que pelo menos comece com um número
      i = float(i)
      lista.append(i)
   else:
      if i=='.':
         print(lista)
         break
      else:
         print('Por favor digite algo válido')
 print('Obrigado por usar o programa')
 #apenas para demonstrar a funcionalidade do exit()

The failure of this program is if someone type a number and then letters, to prevent it from giving problem, you could use Try:

Make mistakes impossible

 lista=[]
    while True:
       i = input('Digite um número (ou "." para encerrar): ').replace(',','.')
       if i[0].isnumeric():
          try:
             i = float(i)
             lista.append(i)
          except:
             print('Digite um número válido')
       else:
          if i=='.':
             print(lista)
             break
          else:
             print('Por favor digite apenas números válidos')
 print('Obrigado por usar o programa')

Browser other questions tagged

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