Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

286
Visualizações
How to use one else statement with multiple if statements

So I'm trying to make a login prompt and I want it to print 'Success' only if there are no errors. This is the code I'm using:

if not is_email(email) or not is_name(name) or password != confirmPassword or not is_secure(password):
    if not is_email(email):
        print('Not a valid email')
    if not is_name(name):
        print('Not a valid name')
    if password != confirmPassword:
        print('Passwords don\'t match')
    if not is_secure(password):
        print('Password is not secure')
else:
    print('Success')

Would there be any way to make this code shorter? I want to make it show all the errors at once so I'm not using elif.

over 4 years ago · Santiago Trujillo
4 Respostas
Responde à pergunta

0

A way to avoid repeating the tests:

ok = True
if not is_email(email):
    print('Not a valid email')
    ok = False
if not is_name(name):
    print('Not a valid name')
    ok = False
if password != confirmPassword:
    print('Passwords don\'t match')
    ok = False
if not is_secure(password):
    print('Password is not secure')
    ok = False
if ok:
    print('Success')

It's not shorter, but it's clear and saves the extra comparisons, so it's faster and not as wasteful.

over 4 years ago · Santiago Trujillo Relatório

0

One way is to use a flag:

has_errors = False

if not is_email(email):
    print(...)
    has_errors = True
...

if not has_errors:
    print("Success!")
over 4 years ago · Santiago Trujillo Relatório

0

How about this?

flags = [is_email(email), is_name(name), password != confirmPassword, is_secure(password)]
prints = ['Not a valid email', 'Not a valid name', 'Passwords don\'t match', 'Password is not secure']

for index in range(len(flags)):
    if flags[index] == False:
        print(prints[index])
over 4 years ago · Santiago Trujillo Relatório

0

Another approach: accumulate the errors into a list, and then you can check the error list for truthiness instead of re-checking all the error conditions. This also saves you from having to maintain another piece of state and have another line of code in each if block to update it.

errors = []
if not is_email(email):
    errors.append('Not a valid email')
if not is_name(name):
    errors.append('Not a valid name')
if password != confirmPassword:
    errors.append('Passwords don\'t match')
if not is_secure(password):
    errors.append('Password is not secure')
print("\n".join(errors or ["Success"]))
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda