Drenek
Drenek

Reputation: 23

Python3 if if else

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

Upvotes: 2

Views: 327

Answers (2)

Mahi
Mahi

Reputation: 21883

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

Upvotes: 2

tooty44
tooty44

Reputation: 7089

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.

Upvotes: -1

Related Questions