I need to check if a character entered in a password contains an integer or not.
password = input("Enter a password:" )
for num in password:
if num.isdigit():
break
else:
print("Your password must contain a number.")
The code above doesn't work because I'm assuming due to python 3 taking every user input as a string, it checks the string and never knows the difference between the string and the integer in the string. How would I get around this?
Your code works fine if you unindent the else
to make it part of the for
:
for num in password:
if num.isdigit():
break
else:
print("Your password must contain a number.")
If it's part of the if
, the else
happens for every character that's not a digit; if it's part of the for
, it happens at the end of the loop if the loop was never broken , which is the behavior you want.
An easier way of writing the same check is with the any
function ("if there aren't any digits..."):
if not any(num.isdigit() for num in password):
print("Your password must contain a number.")
or equivalently with all
("if all the characters aren't digits..."):
if all(not num.isdigit() for num in password):
print("Your password must contain a number.")
Your code will print Your password must contain a number.
for every non-digit character. You need to know if there is a digit in the password or not, then make decision about its validity. So you can use a boolean variable, then if any digit character found in the password, the variable would be True
and after for
loop you will use it for checking the validity of password.
You can do like this:
password = input("Enter a password:" )
good_pass = False
for num in password:
if num.isdigit():
good_pass = True
break
if good_pass == True:
print('Good password!')
else:
print("Your password must contain a number.")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.