Reputation: 23
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
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 elif
s 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
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