I need help with some code id been writing randomly about a passwor keeper
I'd appreciate it so much if the help is beginner friendly.
I tried searching for some ways to merge dicts and the entire app isn't working.
User_password_dict = {" " : " "}
def merge_lists(username, password):
dict_append = {}
dict_append[username] = password
User_password_dict.update
def user_info_collection():
while True:
username = input (f"What is would you like your'e username to be ?\n\t:")
if username in User_password_dict:
print ("you need to change your'e username")
break
else:
password = input(f"Type a password\n\t:")
password_check = input(f"Type your password again \n\t: ")
if password_check != password:
print("you have not input the correct password")
break
else:
User_info = merge_lists(username, password)
return User_info
user_info_collection()
print(User_password_dict)
Okay, so you made a good effort but overcomplicated the dict part.
The merge_lists function is not needed as appending a dict is much simpler than that !!
The key line of code that i added was this:
user_password_dict[username] = password
and i removed a couple of unnecessary parts.
So, this will work:
user_password_dict = {}
def user_info_collection():
while True:
username = input (f"What is would you like your'e username to be ?\n\t:")
if username in user_password_dict:
print ("you need to change your'e username")
break
else:
password = input(f"Type a password\n\t:")
password_check = input(f"Type your password again \n\t: ")
if password_check != password:
print("you have not input the correct password")
break
else:
user_password_dict[username] = password
return
user_info_collection()
print(user_password_dict)
here is the result:
What is would you like your'e username to be ?
:test
Type a password
:blah
Type your password again
: blah
{'test': 'blah'}
Related
First, I just want to say I'm a newbie, and I apologize for the bad explanation and the long post...
So, as a practice, I wrote a simple python login system with a JSON file where the profiles are stored.
Everything was going well, but all of a sudden my code started behaving weirdly.
this is my main.py file:
import json
with open("profiles.json") as f:
profiles = json.load(f)
def main():
print("-----------------Main--------------------")
option = input("[L]ogin | [S]ign up: ").upper()
if option == "L":
login()
elif option == "S":
sign_up()
else:
print("Please select a valid option.")
main()
def login():
print("-----------------Login--------------------")
username = input("Username: ")
password = input("Password: ")
check_credentials(username, password)
def sign_up():
print("-----------------Sign up--------------------")
new_username = None
new_password = None
# check if this username already exists, return to sign up if true
def username_match():
nonlocal new_username
new_username = input("Username: ")
for profile in profiles["profiles"]:
if new_username == profile["username"]:
print("This username is taken.")
username_match()
# loop back if the passwords do not match
def password_match():
nonlocal new_password
new_password = input("Password: ")
confirm_password = input("Confirm Password: ")
if new_password != confirm_password:
print("Passwords do not match.")
password_match()
username_match()
password_match()
security_question = input("Security Question: ")
security_answer = input("Security Question Answer: ")
profiles["profiles"].append({"username": new_username,
"password": new_password,
"security_question": security_question,
"security_answer": security_answer})
with open("profiles.json", "w") as w:
json.dump(profiles, w, indent=2)
check_credentials(new_username, new_password)
def profile_settings():
input("-----------------Options--------------------"
"\n"
"[P] change password | [U] change username"
"\n"
"[S] change security question | [E] add email"
"\n"
"What would you like to do: ").upper()
print("\nThis section is under construction. Please visit later.")
def check_credentials(username, password):
print("\nchecking credentials...\n")
for profile in profiles["profiles"]:
if profile["username"] != username and profile["password"] != password:
print("Wrong username and password, please try again.")
login()
if profile["username"] == username:
print(f"found username: {username}")
if profile["password"] == password:
print(f"found password: {password}")
else:
print("Wrong password, please try again.")
login()
else:
print("Wrong username, please try again.")
login()
profile_settings()
main()
and this is my profiles.json file:
{
"profiles": [
{
"username": "Hakobu",
"password": "123",
"security_question": "favorite food",
"security_answer": "lemon"
},
{
"username": "Mohammed",
"password": "345",
"security_question": "1",
"security_answer": "1"
}
]
}
Here is what I found weird:
When I try to login to a second profile, it tells me, wrong credentials and put me back to the login() function, but it lets me in for the first profile.
when trying to make a new profile through the sign_up() function, it is supposed to automatically log in but beyond the first profile, the second profile created just does the same thing, it tells me, wrong credentials and put me back to the login() function.
when successfully logging in with the first profile, the profile_settings() function gets called. it's supposed to close after inputing anything, but instead it goes back to the check_credentials() function, says I input the wrong username and password, then going to the login() function straight after the profile_settings() function even though I have not called them anywhere in the profile_settings() function
I have no idea why in god's name this happens. It was working fine just a little bit ago. Tried commenting out the code I wrote after it was working but nothing worked. I have a huge headache now and my back hurts.
After learning about stack calls and stack frames, I now know that the issue was simply the for loop getting resumed after exiting the check_credentials() resulting in what seemed to be an infinite loop of that function.
Here is the improved code:
def check_credentials(username, password):
print("\nchecking credentials...\n")
username_found = False
password_found = False
for profile in profiles["profiles"]:
if profile["username"] == username:
print(f"found username: {username}")
username_found = True
if profile["password"] == password:
print(f"found password: {password}")
password_found = True
break
if not username_found and not password_found:
print("Wrong username and password, please try again.")
login()
elif not username_found:
print("Wrong username, please try again.")
login()
elif not password_found:
print("Wrong password, please try again.")
login()
profile_settings()
I have an assignment to make a simple task manager/todo list. This code block is just the part of the program that handles login, new username and password registration. When the user registers that input is written to a text file called user.txt.
Whenever it writes to the text file, it writes like this:(['admin', 'adm1n'])
instead, it should write it like this:admin, adm1n
user_file = open("user.txt","r+")
login = False
while login == False:
new = input("Are you a new user? Y/N:\n").lower()
if new == "y":
print("Please register a new username and password:\n")
new_user1 = input("Please enter a new username:\n").split()
new_pass1 = input("Please enter a new password:\n").split()
new_user2 = input("Please confirm your username:\n").split()
new_pass2 = input("Please confirm your password:\n").split()
user_pass1 = new_user1 , new_pass1
user_pass2 = new_user2 , new_pass2
if user_pass1 == user_pass2:
user_file.write(f"{user_pass2},")
user_file.seek(0)
break
elif new == "n":
username = input("Enter your username:\n")
password = input("Enter your password:\n")
valid_user = username
valid_password = password
for line in user_file:
valid_user, valid_password = line.split(", ")
if username == valid_user and password == valid_password:
login = True
if login == False:
print("Incorrect details! Please enter a valid username and password")
What am I doing wrong? I'm sure it's something small.
Thanks in advance!
Because you are making a tuple there. Instead, you should create a string. Here is the corrected version of your code
user_pass1 = new_user1 + ',' + new_pass1
user_pass2 = new_user2 + ',' + new_pass2
if user_pass1 == user_pass2:
user_file.write(f"{user_pass2},")
user_file.seek(0)
break
Thanks for your feedback everyone.
I managed to get it figured out. I added an index to it to print the string and it worked just fine.
user_pass2 = new_user2 , new_pass2
if user_pass1 == user_pass2:
#Writes username and password to text file in format requested.
user_file.write(f'\n{user_pass2[0]}, {user_pass2[1]}')
I'm aware of the multiple posts and sources regarding how to loop and read from a text file. I'm sorry to be that guy but I'm a recent noob at Python and I'm writing this at 1:00 in the morning.
As the title suggests, how do I loop my login page so that if the user enters details incorrectly then they get another chance to try, until they have entered details correctly. The password/username also needs to be read from an external file.
My code:
print ("\nEnter details to access wallet...\n")
username = 'Janupedia'
password = '12345'
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= £315.37")
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print('\n--------------------------------------------------------\n')
Let's say your text file (credentials.txt) reads:
Janupedia
12345
Maybe something like this will work for you. I've commented the code that I added. You probably want to name the credentials file something else.
print ("\nEnter details to access wallet...\n")
"""
Open File
"""
with open("Credentials.txt", "r") as f:
array = []
for line in f:
array.append(line) #stores username and password
username = array[0]
password = array[1]
login = 0 #initial login status
while login == 0: #as long as login status = 0 loop repeats
userInput = input("Username?")
if username.strip(' \n') == userInput.strip(' \n'):
userInput = input("Password?")
if password.strip(' \n') == userInput.strip(' \n'):
login = 1 #login successful set login status to 1 thus breaking loop
else:
print("Incorrect")
else:
print("Incorrect")
print('\n--------------------------------------------------------\n')
# Login successful loop finished
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= 315.37")
So you want to loop it. Where would a good place for that be? How about when we ask for a question.
Now, look at the condition where we get the right username and password. We don't want to handle it inside the loop. The loop is only there to get the correct username and password.
print("\nEnter details to access wallet...\n")
username = "Janupedia"
password = "12345"
userInput = ""
while userInput != password:
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
break
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print("Welcome!")
print("\n--------------------------------------------------------\n")
print("BTN = 0.10")
print("= £315.37")
todo_list = open("Credentials", "a")
todo_list.write("Username = Janupedia + Password = 12345")
todo_list.close()
print("\n--------------------------------------------------------\n")
Now to read your username/password from a file. Let's make it simple. The first line is the username and the second line is the password. There are no other items.
Now create a proper function.
def read_credentials_from_file(filename):
"""Read the file and return (username, password).
File contents are first line username and second line password.
"""
# Using the `with` statement is current best practice.
with open(filepath, "rt") as user:
username = user.readline().strip()
password = user.readline().strip()
return username, password
Now fix your code to use the function.
username, password = read_credentials_from_file(...)
Note in the function we strip line endings. If you are using Python 3.7, use the breakpoint function to step through the code and watch what it is doing.
do something like this:
password = "password"
username = "username"
theirUsername = input("What is your username")
theirPassword = input("What is your password")
while theirUsername != username or theirPassword != password:
print("incorrect")
theirUsername = input("What is your username")
theirPassword = input("What is your password")
print("correct")
You can read from an external file with file = open("externalfile.txt","r") then do text = file.read() and if the file is formatted as
username
password
do text = text.split("\n") and then username = text[0] and password = text[1]
this is what it should look like with an explanation:
file = open("password.txt","r") #this opens the file and saves it to the variable file
text = file.read() #this reads what is in the file and saves it to the variable text
text = text.split("\n") #this makes the text into a list by splitting it at every enter
username = text[0] #this sets the username variable to the first item in the list (the first line in the file). Note that python starts counting at 0
password = text[1] #this sets the password variable to the second item in the list (the second line in the file)
theirUsername = input("What is your username") #gets username input
theirPassword = input("What is your password") #get password input
while theirUsername != username or theirPassword != password: #repeats the code inside while theirUsername is not equeal to username or theirPassword is not equal to password
print("incorrect") #notifies them of being wrong
theirUsername = input("What is your username") #gets new username input
theirPassword = input("What is your password") #gets new password input
print("correct") #tells them they are corrected after the looping is done and the password and username are correct
I just finished Coursera's Python for Everybody 1st course.
To practice my skills, I decided to make a password and username login. Whenever I create a username, I get my user set error which says 'Invalid credentials'. Here is my code.
import time
import datetime
print ('storingData')
print("Current date and time: ", datetime.datetime.now())
while True:
usernames = ['Admin']
passwords = ['Admin']
username = input ('Please enter your username, to create one, type in create: ')
if username == 'create':
newname = input('Enter your chosen username: ')
usernames.append(newname)
newpassword = input('Please the password you would like to use: ' )
passwords.append(newpassword)
print ('Temporary account created')
continue
elif username in usernames :
dataNum = usernames.index (username)
cpasscode = passwords[dataNum]
else:
print ('Wrong credentials, please try again')
continue
password = input ('Please enter your password: ')
if password == cpasscode:
print ('Welcome ', username)
The code as it appears in my editor
In your code, you have initialized your usernames array right after the while statement. This means that every time it loops back to the beginning, it re-initializes, losing anything that your previously appended. If you move the array initialization outside of the loop, it should work as expected.
This works for python 3. for python 2 you must take input differently refer: Python 2.7 getting user input and manipulating as string without quotations
import time
import datetime
names = ['Admin']
pwds = ['Admin']
while True:
name = input('Name/create: ')
if name == "create":
name = input('New Name: ')
pwd = input('New Pwd : ')
names.append(name)
pwds.append(pwd)
continue
elif name in names:
curpwdindex = names.index(name)
print(names)
curpwd = pwds[curpwdindex]
givenpwd = input('Password: ')
if givenpwd == curpwd:
print("Welcome")
break
else:
print("Inavlid Credential")
else:
print("Wrong Choice")
continue
I need to make a program where I once input username and password, It will verify the input by asking for my username and password again and making me repeat it if it doesn't match. I am stuck on the code below and have no idea how to fix it. Help!
import time
complete = False
user = [["username",""],["password",""]]
def Access():
for n in range (len(user)):
user[n][1] = input(user[n][0])
while not complete:
Access()
username = input("What is the username?")
password = input("What is the password?")
if username == user[n][0]:
print("Good!")
else:
print("Input username again!")
if password == user[n][1]:
print("User has been identified, Welcome",username)
else:
print("Input password again")
Your user isn't stored in the best way possible, try using a dict instead. You can try something like this instead: (fixed some mistakes and made improvements )
# I believe this is what you're trying to do
complete = False
user = {"some username" : "some password", "more username" : "more password"}
while not complete:
username = input("What is the username?")
password = input("What is the password?")
conf_username = input("Repeat the username?")
conf_password = input("Repeat the password?")
# since in your question you said you wanted to ask the user to repeat
if username != conf_username or password != conf_password:
print("username or password does not match") # print a message if different inputs
continue # restarts
if not username in user: # check to see if user does not exists
print("Input username again!")
continue
if password == user[username]: # check to see if password match
print("User has been identified, Welcome",username)
complete = True
else:
print("Input password again")
n is only defined in the Access() function, in your while loop, the program won't know what n is.
in the while section, try if username == user[0][0] and if password == user[1][1]
The code should be like this,n is not defined in while loop:
if username == user[0][0]:
print("Good!")
else:
print("Input username again!")
if password == user[1][1]:
print("User has been identified, Welcome", username)
complete = True
By the way,I suggest you use dictionary structure:
user_pass = {}
while True:
user = input("Your name")
pwd = input("Your password")
if user in user_pass and pwd == user_pass[user]:
print("Welcome", user)
break
else:
user_pass[user]=pwd
print("registration completed,please login")
You are in an infinite while loop because complete is never set to true. Futher you want to match the user name and then password. I made it so you can have a database with names and passwords and compare it with the new input. You can of course also use it with just one username and password. Hope it gives some ideas.
import time
complete = False
user = [["username","password"],["username2","password2"]]
while not complete:
username = input("What is the username?")
password = input("What is the password?")
for n in len(user):
if username == user[n][0]:
print("Good!")
if password == user[n][1]:
print("User has been identified, Welcome",username)
complete = True
else:
break
print("Input password again")
if not complete:
print("Input username again!")
https://github.com/soumilshah1995/UserName-and-Password-Validation-Python
#!/usr/bin/env python3
__author__ = "Soumil Nitin Shah"
__copyright__ = "Copyright 2007, The Cogent Project"
__credits__ = ["Rob Knight"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Soumilshah"
__email__ = "soushah#my.bridgeport.edu"
__status__ = "Testing"
from flask_bcrypt import Bcrypt
class Authentication(object):
def __init__(self, username = ''):
self.username = username
def __lower(self):
lower = any(c.islower() for c in self.username)
return lower
def __upper(self):
upper = any(c.isupper() for c in self.username)
return upper
def __digit(self):
digit = any(c.isdigit() for c in self.username)
return digit
def validate(self):
lower = self.__lower()
upper = self.__upper()
digit = self.__digit()
length = len(self.username)
report = lower and upper and digit and length >= 6
if report:
print("Username passed all checks ")
return True
elif not lower:
print("You didnt use Lower case letter")
return False
elif not upper:
print("You didnt userUpper case letter")
return False
elif length <6:
print("username should Atleast have 6 character")
return False
elif not digit:
print("You didnt use Digit")
return False
else:
pass
enter username = "Youtu1221"
password = "SuperSecret123"
C = Authentication(username=username)
data = C.validate()
bcrypt = Bcrypt()
if (data):
hash = bcrypt.generate_password_hash(username)
print(hash)
else:
pass
check = bcrypt.check_password_hash(hash, "Youtudd1221")
print(check)