Convert int to str for loop

Asked

Viewed 90 times

-1

I would like the variable of input() retain its type int were only converted to string when exclusively entered with’s' digit so that I can exit the loop, without changing the while, there is some function that evaluates or would treat the way I am wanting?

import string
lista = list(string.ascii_lowercase[:6])
while True:
    for i,l in enumerate(lista, start=1):
        print(f"{i}. {l}")
    try:
        vm = int(input("Qual item deseja ou 's' para sair: "))
        if vm == 's':
          break  
    except IndexError:
        print("Tente um indice existente.")  
        break
    except ValueError:
        print("Entre com uma opção existente.")
        break 
  • 1

    Have you thought about seeing if it’s like 's' before making the conversion? If it is 's' you do the break, otherwise make the conversion to int?

  • In what way? Because I could change the while x != ’s', but I intend to know another way.

  • @Allanbelem The answer solved your question? Do you think you can accept it? See [tour] if you don’t know how to do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

1

Do not convert until necessary.

vm = input("Qual item deseja ou 's' para sair: ")
if vm == 's':
    break
vm = int(vm)

I put in the Github for future reference.

But the most correct is to use another variable to save the converted value to int, Just because language allows it does not mean that it is always appropriate to change your type. Repurposing the same variable to a completely different object is one of the cases where it is not good.

  • Exactly, but the vm becomes a string, I want to force with some treatment to obey when it is only a string in exclusive o’s', I believe that if it is possible to make a comparison like this if vm.str(): would be possible through a treatment.

  • It looks like you want to do something wrong, so make it complicated, make it right and simple, other than what I said the code is great, don’t make it worse.

Browser other questions tagged

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