Variable check if the field is not typed in Python?

Asked

Viewed 548 times

0

I need to check if the variable was filled with a name, I tried to check with If and break but the field keeps filling without typing any word.... Below is the code I’m making...

opcao = 0
while opcao != 6:
    print("""\033[32m
Em relação aos contatos do sistema, você deseja...

    1 - Inserir
    2 - Buscar
    3 - Listar
    4 - Alterar
    5 - Excluir
    6 - Voltar
\033[0;0m""")

    opcao = int(input("\033[32mInforme a opção desejada: \033[0;0m"))

    if opcao == 1:
        print("\n\033[47m\033[30m--- Digite os dados do contato ---\033[0;0m\n")

        n = input("Nome: ")
        t = input("Telefone: ")
        e = input("E-mail: ")
        i = int(input("Id: "))

        if n == "":
            print("\n\033[47m\033[30mEspaço vazio! Digite um nome...\033[0;0m")

        if t == "":
            print("\n\033[47m\033[30mEspaço vazio! Digite um login...\033[0;0m")

        if e == "":
            print("\n\033[47m\033[30mEspaço vazio! Digite um senha...\033[0;0m")

        print("\n\033[47m\033[30m--- Contato inserido com sucesso ---\033[0;0m\n")

        inserir_contato(conexao, n, t, e, i)
  • What part of the code did you use the break?

1 answer

0


You printed the message

print("\n\033[47m\033[30mEspaço vazio! Digite um nome...\033[0;0m")

But the code keeps running and inserts the empty name anyway! You can only enter the name if it is filled in.

One way is to use the break like you said, but that keyword only works inside a repeat block like for or while:

while True: 
    n = input("Nome: ")
    if n == "":
        print("\n\033[47m\033[30mEspaço vazio! Digite um nome...\033[0;0m")
    else:
        break

That way the structure will endlessly repeat (while True) and will only stop when you arrive at break, in this case, if the user does not leave the field blank (else).

In other words: if the user leaves the field blank, the error message will be printed and the code will repeat, until the user type a name, causing the code to exit the repetition through the break.

  • Got it, so I already do the variables n, t, e, i inside the while with the check and not separated as I did is this?

  • The purpose of the command while is to repeat a part of the code. You have to put inside the while everything you want to repeat. If you make a while only, and the user misses on the last question, python will repeat the while whole, that is, all the questions that are within the while will appear again. So it is recommended to make a while separate to each question... So if the user misses a question, the system shows the error message and repeats only that question. In the future when learning more you can do a function to not have to write the same code several times.

Browser other questions tagged

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