Password verification in Python - python

I am studying Python for a little while and trying to resolve following problem:
Part of verification routine is given below. When the user enters the password, it is checked to ensure it is between 8 and 15 characters and then requested to verify the password by typing it again. Require complete task(a) CONDITION 1, CONDITION 2, and task (b) IF ... ELSE statement. Code and test the program.
password1 = input("Please enter a new password, between 8 and 15 characters: ")
match = False
while CONDITION 1
while CONDITION 2
password1 = input ("Password must be between 8 and 15 characters - please re-enter: ")
endwhile
password2 = input ("Please verify password: ")
if ....
print
else
endif
endwhile
I complete the task (b) but in task (a) I have a problem with while loop condition "while match:". When I leave variable match = False and enter the password with required amount of characters the loop terminates straight away and does not do verification with if .. else statement. If I write match = True and on first attempt enter incorrect number of characters (with correct number it terminates the loop again) program goes for verification anyway ignoring the number of characters. If the password was the same (example 111 and 111) it goes back to the loop and asks again for the password with required amount of characters. Then if I enter after the right amount of characters and password verification is the same it terminates the program like it suppose to be. I think something with the condition "match" in while loop is not right but can't figure out what it should be. Thanks
password1 = input("Please enter a new password, between 8 and 15 characters: ")
match = True
while len(password1) < 8 or len(password1) > 15:
password1 = input ("Password must be between 8 and 15 characters - please re-enter: ")
while match:
password2 = input ("Please verify password: ")
if password1 == password2:
print ("Password is valid")
break
else:
print ("Password is invalid")

I think like myself you are new to this. I find the following wrong with your code interpretation of the problem:
Condition 1 and 2 are misplaced
If statement is in the wrong loop.
Your match is also not switched.
Check this out:
def password_verification():
password1 = input('Please enter a new password, between 8 to 15 characters: ')
match = False
while match is False:
while len(password1) < 8 or len(password1) > 15:
password1 = input('Password must be between 8 to 15 characters - please re-enter password: ')
password2 = input('Please verify password: ')
if password1 == password2:
print('Password is valid')
match = True
else:
print('Password is invalid')
return match
password_verification()

You are matching only when the first time wrong number of characters were entered. What will happen if in the first time, user enters between 8 to 15 characters? The first while loop will not execute, and hence nothing will execute. Condition1 (length between 8 and 15) must be checked outside the loop, and the second while loop must be kept separate.
pass1 = input('Enter a password : ')
while len(pass1) < 8 or len(pass1) > 15:
print('Incorrect, try again')
pass1 = input('Enter a password : ')
# Program reaches here only if pass1 is between 8 to 15 characters, otherwise first loop will be infinite
pass2 = input('Verify the password : ')
if pass1 == pass2:
print('Valid')
else:
while pass1 != pass2:
pass2 = input('Invalid. Re-enter the correct password : ')
The above code first takes password1, checks if it is within the 8-15 characters range. If it is not, the first while loop keeps on executing. When a valid input is given, it takes password2, and checks for equality. If it matches for the first time, no further while loop is needed. If it doesn't match, the while loop keeps on executing till equal passwords are not provided. Hope this helps!

Related

Program to prompt password

I'm trying to create this python program that will prompt the user to enter a password. However, the password has to be between 6 and 12 characters. Also it must have a "#" in it but not in the first character or last. This is what I have so far, I'm not sure what I'm doing wrong I just keep getting the "Not a valid password" response. Any help would be greatly appreciated. Thank You
# This program will determine whether a password meets all security requirements
import re
print ("Hello, please enter a password between 6 and 12 characters.")
print ("The password may consist of a combination of numbers and letters, but the one of characters (after the first and before the last) must be a # sign.")
password = input("Please enter your password: ")
x = True
while x:
if (len(password)<6 or len(password)>12):
break
elif not re.search("[a-z]", password):
break
elif not re.search("[0-9]", password):
break
elif not re.search("[A-Z]", password):
break
elif not re.search("[#]", password):
break
else:
print("Valid Password")
x = false
break
if x:
print("Not a valid password")
# This program will determine whether a password meets all security requirements
import re
print ("Hello, please enter a password between 6 and 12 characters.")
print ("The password may consist of a combination of numbers and letters, but the one of characters (after the first and before the last) must be a # sign.")
is_valid = False
while not is_valid:
password = input("Please enter your password: ")
if (len(password)<6 or len(password)>12):
print('Password is the wrong length')
continue
if not re.search("[a-z]", password):
print('Password missing lowercase letter.')
continue
if not re.search("[0-9]", password):
print('Password missing a number.')
continue
if not re.search("[A-Z]", password):
print('Password missing uppercase letter.')
continue
if re.search("^#", password) or re.search("#$", password):
print('Password cannot begin or end with #.')
continue
print("Valid Password")
is_valid = True
I think this is roughly what you're trying to do, you can improve it to fit your use case. The way you have your loop currently it will only ever run once, the break statement exits the loop if it hits one of your conditions. The while statement never gets a chance to check the x variable you set to false.
I modified the loop so it will repeatedly prompt until the password fits the format you specified. You could also add a prompt to quit or try another password for a better user experience. I modified your # check so the regex checks if it is either at the beginning or the end of the password.
Also I changed all your conditions to if statements. The order the conditions are checked is important, and could potentially hid a false condition. Like the classic FizzBuzz problem.

How to make my code break out of loop and actually detect a certain input

I am doing a basic Python assessment on a password vault but am getting errors that I can't seem to solve myself. and btw guys I didn't come here for a grammar and punctuation lesson, so if you are just here to edit my question and not offer any assistance please dont bother.
For example, in this part of the code I want the user to input 1 or 2, and if he selects 1 it asks him to log in, while if he selects 2 it asks him to register. But at the moment it is completely ignoring the parameters and accepting anything.
Another problem is that when the user enters the valid password, instead of just stopping at password correct, it for some reason re-asks "what is your username."
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()
----------------------------------------------------------#Full code begins now
l_p = ""
print("------------------------------------------------------------------------")
print('''Welcome to password Locker, a place where you can
store all your passwords to easily enter your precious accounts without
hassle.''')
print("------------------------------------------------------------------------")
print('''First lets make an account,''')
while True:
first_name = input('''What is your first name?
''')
if first_name.isdigit(): #isdigit, detects if there
print("Please enter a valid answer, No nubers shoud be present")
elif first_name == "":
print("Please enter an answer")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break #the break loop exits the current loop and continues with the next programes following it
while True:
sur_name = input('''What is your surname?
''')
if sur_name.isdigit(): #isdigit detects if the
print("No numbers")
elif sur_name == "":
print("Please enter an answer")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break
print('''------------------------------------------------------------------------''')
print('''Welcome, {} {}
what would you like your username to be, it should be something
memorable and no longer than fifteen characters long, '''.format(first_name, sur_name))
while True:
input_username = input("")
if 0 < len(input_username) < 16:
print('''Nice, username''')
break
elif input_username == "":
print("Please enter an answer")
else:
print('''Your username should be a maximum of 15 charecters, ''')
print('''-------------------------------------------------------------------------''')
while True:
input_lockerpassword = input('''Now it's time to setup a password for your locker, It should be between 4
and 10 charecters long,
''')
if len(input_lockerpassword) > 4 and len(input_lockerpassword) < 11:
print('''{}, is locked in thanks for joining Password Locker'''.format(input_lockerpassword))
break
else:
print("It should be between 4 and 10 charecters long!")
print('''
-------------------------------------------------------------------------------------------''')
def login_originup1():
print(''' Welcome to password vault, You can either login or create a New account''')
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()```
Ok, first of all, you should know that the input() function returns a string and, as such, your first condition : if login_orsignup1 != 1 will always be true, because the string object '1' isn't equal to the int object 1. As for why you get asked again for the user after having a good password, that is because the break statement only breaks from the current loop. So you only break of this loop to get back at the start of your username verification loop. I would suggest a cleaner implementation like so :
# login or sign-up loop
while True:
login_orsignup1 = input(" Press \n1) to Log in \n2) to register a new account")
# you can have the input result in a variable like so, if you want to use it later on
if login_orsignup1 == "1": # you said '1' was for login, right?
# or you can test this directly in your if statement
# if it is only needed for this condition
while input("What is your username: ") != username:
print("Incorrect username")
# same thing for password, but could be implemented another way if you
# don't want to loop until the user gets the correct password
while input("What is your password: ") != input_lockerpassword:
print("Incorrect password for this username")
# your code gets here only if the user entered the right credentials
# so you can now break of the login or sign-up loop
break
elif login_orsignup1 == "2":
# code for registration here
This could be good enough for a simple thing. I would recommend designing this console program by following concepts of a state-machine and adding more code at each step to handle cases like going back one step or back at the start.
Hope this helps
the problem is in your login_originup1 function you are making three While loops that the program can't escape from in your function you are asking if login_orsignup1 != 1
without an else statement so if the user wanted to login he would press input in "1" then the program will say that
"1" =! 1 is false
it will look for an else statement But not find one so it will go back to the start of the loop and ask the user to input again. this is it for the First Loop.
Now if the user Inputs in "2" (which means that the user wants to register) it will make him log-in because:
"2" =! 1is true
and will continue to the next while loop in here you will be asking for the username and the user will give the username. Now this is it for the Second Loop
we now go to the last loop where you ask for the Password and the User Will give the Password. The program Will either 1. say that it was false and ask for the password again or 2. it will accept the password and Break the While loop. Now this is it for the Third Loop
so why is it asking me for the Username Because the break statement breaks only the while loop it is in so that break statement broke only the third while loop and was back to the Second Loop which the Second Loop will bring us back into the Third Loop again
so how to fix this?
simple like this:
def login_originup1():
print('Welcome to password vault, You can either login or create a New account')
while True:
login_orsignu = input('Press\n1) to Log in\n2) to register a new account\n')
loopBreaker = 0
if loopBreaker:
break
if int(login_orsignu) != 1:
while True:
if loopBreaker:
break
username = input('What is your,\nUsername:')
if input_username == username:
l_p = input('What is your password ')
while True:
if loopBreaker:
break
if l_p == input_lockerpassword:
print("Password Correct")
loopBreaker = 1
break

How to replace a double while loop?

The program, which assesses password strength, initially checks whether the length of the password is correct (6-12) and whether the password contains extented ASCII characters, i.e. 127-255.
The problem I have is that if the user first inputs a password which is too short or too long, the program then doesn't check for extended characters in the next password, inputted by the user and vice-versa, with checking for extended characters first.
I implemented a double while loop, if that's the correct way of calling it, however it still didn't bring the desired effect.
import re
import time
#score variable, responsible for later defining if passwords is weak, medium or strong
Score = 0
#list for improvements to password printed out with score at the end
Improvements = []
Password = ""
#defines function for checking for presence of extended characters (i.e. ascii 128-255)
def hasExtended(s):
return any(ord(i) > 127 for i in s)
#inputs password
Password = input("Please enter a password:")
Password_length = len(Password)
Extended_presence = hasExtended(Password)
#checks password length (6-12), asks user to re-input until password is within boundaries
#checks if password contains extended characters
#double while loops to allow for two conditions simultaneously
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
while Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
while Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
else:
#defines function for checking for presence of numbers
def hasNumbers(s):
return any(i.isdigit() for i in s)
#defines function for checking for presence of letters
def hasLetters(s):
return any(i.isalpha() for i in s)
#defines function for checking for presence of special characters
def hasSpecial(s):
return any(ord(i) < 48 for i in s)
#checks if password contains letters
Letter_presence = hasLetters(Password)
if not Letter_presence:
Score = Score - 1
Improvements.append("letters")
else:
Score = Score + 1
#checks if password is all upper case
Is_upper = Password.isupper()
if not Is_upper:
Score = Score + 1
else:
Score = Score - 1
Improvements.append("upper and lower case letters")
#checks if passwords is all lower case
Is_lower = Password.islower()
if not Is_lower:
Score = Score + 1
else:
Score = Score - 1
Improvements.append("upper and lower case letters")
#checks if password contains a number
Number_presence = hasNumbers(Password)
if not Number_presence:
Score = Score + 0
Improvements.append("numbers")
else:
Score = Score + 1
#checks if password is just numbers
Only_numbers = Password.isdigit()
if not Only_numbers:
Score = Score + 0
else:
Score = Score - 1
Improvements.append("other characters")
#checks if password contains special characters
Special_presence = hasSpecial(Password)
if not Special_presence:
Score = Score + 0
Improvements.append("special characters, such as '$'")
else:
Score = Score + 1
#outputs weak, medium or strong password to user and suggest improvements
if Score <= 2:
print("The program is processing your password...")
time.sleep(2)
print("Your password isn't acceptable! Please try again.")
print("Next time, remember to include", Improvements)
if Score == 3:
print("The program is processing your password...")
time.sleep(2)
print("Your password is weak, you should try again.")
print("Next time, remember to include", Improvements)
elif Score == 4:
print("The program is processing your password...")
time.sleep(2)
print("Your password is medium, it should be OK.")
print("Next time, remember to include", Improvements)
elif Score == 5:
print("The program is processing your password...")
time.sleep(2)
print("Your password is strong, it is absolutely fine.")
I would suggest you to write validator, a function that looks like this:
def validate_password(password):
... # check score, symbols and other, print whatever you want
return score
And then call it in a way like that one:
pass = input('Enter your password')
score = validate_password(pass)
while score <= 3:
pass = input('Enter another password')
score = validate_password(pass)
You can implement such scenario like below:
check_pass function will check for length of function
def hasExtended(s):
return any(ord(i) > 127 for i in s)
check_pass = lambda x: x>=6 and x<=12 # check for range of input value
password=input("Password: ")
if check_pass(len(password)) and not hasExtended(password):
print("Valid password")
else:
print("Do not use extended ascii characters, use password with minimum length of 6 and maximum length of 12")
to be more precise about error you can use nesting in below way:
if check_pass(len(password)) and not hasExtended(password):
print("Valid password")
elif check_pass(len(password)) and hasExtended(password):
print("do not use extended ascii character")
elif not check_pass(len(password)) and hasExtended(password):
print("password length should be between 6 to 12")
similarly if you want to check for invalid length of minimum lenght and maximum length separately.
If you wish to check all condition separately and then show success or failure you can do like below:
def verify_password(password):
if len(password) < 6:
print("require minimum 6 characters")
if len(password) > 12:
print("can not use more then 12 characters")
if hasExtended(password):
print("use only valid ascii characters")
else:
print("valid password")
return True
while not verify_password(password): # loop will never stops unless valid password or used break statement within
password = input("Password: ")
The function will check for three different condition if condition satisfied message will be printed else it will continue executing, at the end if it is valid password instead of printing anything it will print valid password and return True instead of None.
Try this code , and instead of while just use if in first checking codition of Extended_presence , You don't need while there because its already in the scope of previous while loop :
import re
print([chr(i) for i in range(127,200)])
import re
import time
#score variable, responsible for later defining if passwords is weak, medium or strong
Score = 0
#list for improvements to password printed out with score at the end
Improvements = []
Password = ""
#defines function for checking for presence of extended characters (i.e. ascii 128-255)
def hasExtended(s):
return any(ord(i) > 127 for i in s)
#inputs password
Password = input("Please enter a password:")
Password_length = len(Password)
Extended_presence = hasExtended(Password)
#checks password length (6-12), asks user to re-input until password is within boundaries
#checks if password contains extended characters
#double while loops to allow for two conditions simultaneously
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
if Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
while Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
output:
Please enter a password:hel¢
Your password is too short . It has to be no shorter than 6 characters .
Please enter a password:hello¢
Your password contains characters from the extended ASCII list. Please don't use these.
Please enter a password:hello¢
Your password contains characters from the extended ASCII list. Please don't use these.
Please enter a password:hellllo#
Why don't you delegate your password check to a function and separate the user input from checking the password? That way you can ask the user as many times as you want without complex jumps. Something like:
def validate_password(password):
if len(password) < 6:
return 0, "Your password is too short, it has to be no shorter than 6 characters."
elif len(password) > 12: # why, tho?
return 0, "Your password is too long, it has to be no longer than 12 characters."
# these can be optimized but I'll leave that as an exercise for you
if any(ord(i) > 127 for i in password): # again, why?!
return 0, ("Your password contains characters from the extended ASCII list. "
"Please don't use these.")
score = 0
improvements = []
if any(i.isalpha() for i in password):
score += 1
if password.isupper() or password.islower():
score -= 1
improvements.append("upper and lower case letters")
else:
score += 1
else:
score -= 1
improvements.append("letters")
if any(i.isdigit() for i in password):
score += 1
if password.isdigit():
score -= 1
improvements.append("other characters")
else:
# score -= 1 # are you sure you don't want to reduce the score?
improvements.append("numbers")
if any(ord(i) < 48 for i in password):
score += 1
else:
# score -= 1 # are you sure you don't want to reduce the score?
improvements.append("special characters such as '$'")
return score, "Next time remember to include: {}".format(", ".join(improvements))
And now you can call it from wherever you want, as many times as you need:
while True:
candidate = input("Please enter a password: ")
print("The program is processing your password...") # why? this happens in an instant
score, message = validate_password(candidate)
time.sleep(2) # why are we making people wait for no reason?
if score <= 1:
print(message)
print("Please try again.")
elif score == 2:
print("Your password is weak, you should try again.")
print(message)
elif score == 3:
print("Your password is medium, it should be OK.")
print(message)
break
elif score == 4:
print("Your password is strong, it is absolutely fine.")
break
print("Accepted password: " + candidate)
And you can get an output as:
Please enter a password: dfld
The program is processing your password...
Your password is too short, it has to be no shorter than 6 characters.
Please try again.
Please enter a password: dfldsadlslads
The program is processing your password...
Your password is too long, it has to be no longer than 12 characters.
Please try again.
Please enter a password: dflds°
The program is processing your password...
Your password contains characters from the extended ASCII list. Please don't use these.
Please try again.
Please enter a password: ddlllsd
The program is processing your password...
Next time remember to include: upper and lower case letters, numbers, special characters
such as '$'
Please try again.
Please enter a password: ddlllsd12
The program is processing your password...
Next time remember to include: upper and lower case letters, special characters such as '$'
Please try again.
Please enter a password: Ddlllsd12
The program is processing your password...
Your password is medium, it should be OK.
Next time remember to include: special characters such as '$'
Accepted password: Ddlllsd12

How to check the "password" for numbers in python

I have set up a program to change a "password". I have it checking to see if it is at least 8 characters, contains a capital letter and has a number, and if it does not meet this criteria, it asks for the password again. I have everything working except the checking for a number and I was wondering if someone could help.
npwv = 1
while npwv == 1:
npw = input("Please enter new password.")
npwc = input ("Please confirm new password")
if npwc == npw:
if npwc.isupper()== False:
if npwc.islower()== False:
if len(npwc) >= 8:
if str.isdigit(npwc) == True:
npw=npwc
print("Your password has been changed")
else:
print("Your password must contain a number")
npwv = 1
else:
print("Your password must contain at least 8 characters.")
npwv = 1
else:
print("Your password must contain at least 1 upper case character.")
npwv = 1
else:
print ("Passwords don't match")
npwv = 1
You are checking if the password itself is fully uppercase or composed of numbers. What you need to check if if the characters in the password match this criteria.
has_upper = any([c.isupper() for c in npwc])
has_digit = any([c.isdigit() for c in npwc])
You can also use regular expressions.
By the way, you should prefer getpass to get the password from the user.
Have you considered using .isalnum()?
>>> foo = "123asd"
>>> foo
'123asd'
>>> foo.isalnum()
True
>>>
Edit: Judging by the other answers, I am not sure what are you looking for, could explain it with examples?
I would suggest using sets, and the string package from stdlib for your list of acceptable characters.
I would also suggest refactoring a bit to remove a lot of the nesting with if / else branches.
import string
upper = set(list(string.uppercase))
lower = set(list(string.lowercase))
numbers = set(list(string.digits))
while True:
npw = input("Please enter new password: ")
npwc = input("Please confirm new password: ")
if npwc != npw:
print("Passwords don't match")
continue
if len(npcw) < 8:
print("Your password must contain at least 8 characters.")
continue
chars = set(list(npwc))
if not upper.intersection(chars):
print("Your password must contain at least 1 upper case character.")
continue
if not lower.intersection(chars):
print("Your password must contain at least 1 lower case character.")
continue
if not numbers.intersection(chars):
print("Your password must contain a number")
continue
npw = npwc
print("Your password has been changed")
break
This can be made more compact but yeah..
while True:
npw = input("Please enter new password.")
npwc = input ("Please confirm new password")
if npwc == npw:
if any(x.isupper() for x in npwc):
if any(x.islower() for x in npwc):
if len(npwc) >= 8:
if any (x.isdigit() for x in npwc):
npw=npwc
print("Your password has been changed")
#break # you probably want to exit the loop at this point
else:
print("Your password must contain a number")
else:
print("Your password must contain at least 8 characters.")
else:
print("Your password must contain at least 1 upper case character.")
else:
print("Your password must contain at least 1 lower case character.")
else:
print("Passwords don't match")
This looks like a job for regular expressions. Solution below:
import re
def password_validator(password):
if len(password) < 8:
return False, "Your password must contain at least 8 characters"
if not re.match('.*[0-9]', password):
return False, "Your password must contain a number"
if not re.match('.*[A-Z]', password):
return False, "Your password must contain at least 1 upper case character."
if not re.match('.*[a-z]', password):
return False, "Your password must contain at least 1 lower case character."
return True, "Your password has been changed"
while True:
npw = input("Please enter new password.")
npwc = input("Please confirm new password")
if npw != npwc:
print("Passwords don't match")
continue
is_valid, message = password_validator(npw)
print(message)
if is_valid:
break
You could also validate the whole thing in one go as:
pattern = """
(?=.*[a-z]) # use positive lookahead to see if at least one lower case letter exists
(?=.*[A-Z]) # use positive lookahead to see if at least one upper case letter exists
(?=.*\d) # use positive lookahead to see if at least one digit exists
[A-Za-z0-9##$%^&+=]{8,} # match any character in [] at least 8 times
"""
pwd_validator = re.compile(pattern, re.VERBOSE)
if pwd_validator.match(password):
# legit password
else:
# no match ask again
Hope this helps. The re.VERBOSE just makes this regular expression self-documenting so a lot easier to understand in future.

Python: What is Wrong with these two Functions?

I came across a problem within my program that I'm writing. I've narrowed down the problem to these two functions. The problem occurs when you call the function enterPasswords, enter invalid data such as 'a', then break out of the passwordLength function by entering valid data such as 'hello'. I've left some print statements there to help you see the problem. I've tried adding returns, but the same problem still occurs.
Any advice will be greatly appreciated. If you could tell me why the problem is occurring, I'm sure I could fix it myself. Thanks.
def passwordLength(password):
if (len(password) < 4) or (len(password) > 15):
print("Error from server: Your password must be at least four and at most fifteen characters long.")
enterPasswords()
def enterPasswords():
password = input("Input password: ")
passwordLength(password)
print(password)
password2 = input("Re-enter password: ")
print(password, password2)
enterPasswords()
Here is an image of my problem (What I'm wanting to know is, why isn't the program ending where I've highlighted, why does it carry on, and why is 'a' being printed towards the end?):
http://i.imgur.com/LEXQFTO.png
It appears that if the user inputs an invalid password at first, it repeats enterPasswords - however, if the user completes this successfully, it goes back to the initial enterPasswords. Instead, try
def passwordLength(password):
if (len(password) < 4) or (len(password) > 15):
print("Error from server: Your password must be at least four and at most fifteen characters long.")
return False
return True
def enterPasswords():
password = input("Input password: ")
while not passwordLength(password):
password = input("Input password: ")
print(password)
password2 = input("Re-enter password: ")
print(password, password2)
This will continue to ask the user to reinput the first password until it is valid, and only then it will ask the user to confirm.
The password variable in passwordLength() is completely unrelated to the variable in enterPasswords(). The behaviour might also not be as you expect it to be. Try something like this:
def passwordLength(pw):
return 4 <= len(pw) <=15
def getPw():
return input("Enter password: ")
def enterPasswords():
pw = getPw()
while not passwordLength(pw):
print("Incorrect password length.")
pw = getPw()
# ...
Your functions are calling each other in a bad way. If you try to follow line by line your algorithme (using the case you mentioned with 'a' and 'hello') you will probably see the problem.
Here is a solution :
def passwordLength(password):
if (len(password) < 4) or (len(password) > 15):
print("Error from server: Your password must be at least four and at most fifteen characters long.")
return False
else : return True
def enterPasswords():
passwordOK = False
while not passwordOK :
password = input("Input password: ")
passwordOK = passwordLength(password)
print(password)
password2 = input("Re-enter password: ")
print(password, password2)
enterPasswords()

Categories