2

When i do this in this way

x = "Hello"
if len(x) <= 9:
    print("The password must contain at least 9 letters")
if x[0].islower():
    print("The first password letter must be uppercase")
else:
    print("Password saved")
    password = x

i getting

>The password must contain at least 9 letters
>Password saved

What should I do to make the program stop on:

>The password must contain at least 9 letters
1
  • 1
    Use if-elif-else. Commented Jan 22, 2017 at 1:59

2 Answers 2

2

Use elif between if and else:

x = "Hello"
if len(x) <= 9:
    print("The password must contain at least 9 letters")
elif x[0].islower():
    print("The first password letter must be uppercase")
else:
    print("Password saved")
    password = x

elif is executed only when if wasn't executed, and elif's condition is true. You can also chain as many elifs as you want, in which case the first elif whose condition matches is executed.


Update: Since OP said in comments that he wants all errors to be shown at once, I would use something like this:

x = "Hello"
errors = []
if len(x) <= 9:
    errors.append("The password must contain at least 9 letters")
if x[0].islower():
    errors.append("The first password letter must be uppercase")

if errors:
    print('\n'.join(errors))
else:
    print("Password saved")
    password = x
Sign up to request clarification or add additional context in comments.

Comments

-1

The problem is that you have two if filters in the code. I'm assuming you want the structure where both "The password must contain at least 9 letters" and "The first password letter must be uppercase"can be returned if both their conditions are met.

If, however, you don't need this capability, simply replace the second if with an elif and it should work.

If you need this capability, try something like:

x = "Hello"
if len(x) <= 9:
    print("The password must contain at least 9 letters")
if x[0].islower():
    print("The first password letter must be uppercase")
if len(x) >= 9 and x[0].isupper():
    print("Password saved")
    password = x

This simply adds a third if statement testing that the previous conditions were fulfilled.

1 Comment

It is hardly a good idea to make the final if statement re-calculate the conditions (in reverse) that were already verified. This doubles the computational complexity! See my answer for a way to re-use the calculated values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.