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()
Related
I'm practising my coding - pretty new to this - and i'm trying to create a login system, all is working well so far but i'm trying to use a while loop to maximise the number of user attempts at inputting the correct password. Even if the user inputs the correct password, the loop will carry on until the loop is completed and will continue to say carry on.
login = {
"alex": "dog123"
}
passkey = login.values()
correct_user = True
while correct_user:
user = input("Please input your username ")
if user in login:
print(f'Hello {user}, please input your password.')
correct_user = False
else:
print("Invalid user")
attempt = 0
max_attempts = 3
correct_password = True
while correct_password:
password = input(">")
if password in passkey:
print(f"""Welcome back {user}!
How can i help you today?""")
correct_password = False
else:
while attempt < max_attempts:
print("try again")
attempt += 1
password = input(">")
if password in passkey:
correct_password = False
else:
print("too many guesses!")
break
Try this.
login = {
"alex": "dog123"
}
passkey = login.values()
correct_user = True
while correct_user:
user = input("Please input your username ")
if user in login:
print(f'Hello {user}, please input your password.')
correct_user = False
else:
print("Invalid user")
attempt = 0
max_attempts = 3
correct_password = True
while correct_password:
if attempt < max_attempts: # checks if an attempt is left.
password = input(">")
if password == login[user]: # Check password equal current userpassword.
print(f"""Welcome back {user}!
How can I help you today?""")
correct_password = False
else:
print("Invalid password")
attempt += 1
else: # print too many attempts
print("Too many attempts")
correct_password = False
Don't use password in passkey to check that if password is correct or not. Why?
Explanation
Let say you have more than one users
login = {
"alex": "dog123",
"alice": "cat123"
}
If you use in and check that if password is in passwords list then you face a bug
When
Example
If user is equal alex and password is cat123 then you code don't print that password is incorrect.
So use == and check if password == login[user] here user and password are the one that user enters.
"#alex comments. what does the '[user]' aspect mean?".
#alex if you want all values from the dictionary then you use dict.values(), But if you want a specific key's value then you use dict['Key'] or dict.get('Key'). Let's say user='alex' then login[user] gives the value of the user from the login dict which is 'dog123'. Note if the user is not in the dict then it will give you a KeyError. But if you use dict.get(user) it will return the value of user or None if user is not in dict
Your error comes from breaking out of the inner while loop but still having the outer one running; it's better to use only one loop (and you don't need the 'correct_password' flag any more):
attempt = 0
max_attempts = 3
passkey = ['sesame']
while attempt < max_attempts:
password = input(">")
if password in passkey:
print(f"""Welcome back {user}! How can i help you today?""")
break
else:
attempt += 1
if attempt < max_attempts:
print("try again")
else:
print("too many guesses!")
As a side note, codester_09 is right about the way you check the password, so implement their modification too.
I am tinkering with some code online and stumbled upon this one :
import os
import time
#Must Access this to continue.
def main():
while True:
UserName = input ("Enter Username: ")
PassWord = input ("Enter Password: ")
if UserName == 'Bob' and PassWord == 'rainbow123':
time.sleep(1)
print ("Login successful!")
logged()
else:
print ("Password did not match!")
def logged():
time.sleep(1)
print ("Welcome to ----")
main()
I am trying to make it so after the username and password has been implemented, that this sequence happens next:
def mainname():
while True:
Firstname = input("Enter First Name:")
Lastname = input("Enter Last Name:")
if Firstname == 'Cher, Madonna':
time.sleep(2)
print("May I have your autograph, please?")
else:
print("that's a nice name")
mainname()
But what happens is, after I put in the username and password it then loops back to inputting the username and password. How do I make it so after the username and password has been implemented, then it goes to the first name and last name sequence? Thank you very much for the help
The code that checks the password is in a while True: loop, so it will keep looping and asking for the password regardless.
You want to break out of the loop on success, so add a break after you successfully log in.
Right after you have confirmed that the password is correct just add break. This will end the while loop as the correct username and password is entered.
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.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I'm very new at Python, and I'm trying to make a simple program that asks the user for a password, and if the user didn't guess the password they were asked, ask again until they guess it. How do I do that?
Password = input("guess the password: ")
while (password) != "12345":
Print(input("try again : "))
Welcome to Programming and StackOverflow. Have a look a this Example,
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('Loop ended.')
The break statement ends the while loop.
#g23's Answer is more apt in the context of the question
Make sure your capitalization is right, generally variables are lowercase, but you need to be consistent.
Also when you ask for the password again, you need to store what the user gives you so it can be checked in the loop condition (the while password != "12345": part)
Something like
password = input("Enter the password: ")
while password != "12345":
password = input("try again: ")
This code does what you want. It has a while loop to check if the password was guessed until the right password is entered. Then it has an if statement to write a message: if the right password is entered, it writes it.
password = input("Enter the password: ")
while password != "12345":
password = input("try again: ")
if password == "12345":
print("Correct password!")
Function check whether user's password qualifies, as far as alphanumeric characters, 10 characters length min, and lower and uppercase characters.
def is_good_password(password):
count_upper, count_lower = 0, 0
for characters in password:
if characters.isupper():
count_upper += 1
if characters.islower():
count_lower += 1
is_password_good = True
if len(password) <= 10:
print "Password Is Too Weak, Must Be More Than 10 Characters Long!"
is_password_good = False
if set(database).intersection(password):
print "Password Must Contain Alphanumeric Characters!"
is_password_good = False
if count_upper < 1 or count_lower < 1:
print "Password Must Contain at Least One Uppercase and One Lowercase Character!"
is_password_good = False
create_user(database)
print "Welcome! Username & Password Successfully Created!"
return is_password_good
I want the create_user() function raw_input for passcode to return back to passcode if the user's password doesn't qualify on the above function; however, the create_user() function returns the passcode raw_input back to the user raw_input if the password doesn't work.
How can I fix this?
Thanks
def create_user(database):
good_user = False
good_pass = False
while not good_user or not good_pass:
user = raw_input("Enter a New Username: ")
good_user = is_good_user(user)
passcode = raw_input("Enter a New Password: ")
good_pass = is_good_password(passcode)
database[user] = passcode
dump_data()
Just add another loop; you don't need to use flag variables either, just use break to end the loop when you have a good user or password:
while True:
user = raw_input("Enter a New Username: ")
if is_good_user(user):
break
print "That's not a good username, please try again"
while True:
passcode = raw_input("Enter a New Password: ")
if is_good_password(passcode):
break
print "That's not a good password, please try again"
database[user] = passcode
dump_data()
Did I understand you correctly?
def create_user(database):
good_user = False
good_pass = False
while not good_user:
user = raw_input("Enter a New Username: ")
good_user = is_good_user(user)
while not good_pass:
passcode = raw_input("Enter a New Password: ")
good_pass = is_good_password(passcode)
database[user] = passcode
dump_data()