Checking to see if username already exists - python

Starting at "#If user does not have account:" the code is printing the output multiple times. I just want it to print the output (either the username is taken or they can continue) once. Then, I want the password to be typed twice and compared to make sure that they match. Can you help me fix this issue?
import colorama
colorama.init()
print_in_green = "\x1b[32m"
print_in_red = "\x1b[31m"
print_in_blue = "\x1b[36m"
print_in_pink = "\x1b[35m"
print_default = "\x1b[0m"
#STAGE 1: Opening the files and grabbing data
users_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt"
passwords_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt"
scoreslist_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt"
def get_file_contents(file_path):
return [line.strip() for line in open(file_path)]
scoreslist = get_file_contents(scoreslist_path)
def add_file_contents(file_path, contents):
with open(file_path, "a") as file:
file.write(contents)
def login_user(new_account=False):
usernameslist = get_file_contents(users_path)
passwordslist = get_file_contents(passwords_path)
if new_account:
response = 'y'
else:
response = input("-"*50 + "\nWelcome! Do you have an account (y/n)? ")
print("-"*50)
#If user has an account:
if response == "y":
goodlogin = False
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for id in range(len(usernameslist)):
if username == usernameslist[id] and password == passwordslist[id]:
goodlogin = True
if goodlogin:
print(print_in_green + "Access granted!" + print_default)
#Ask if user would like to view leaderboard
leaderboard = input("Would you like to view the leaderboard (y/n)? ")
#If thet want to see scores:
if leaderboard == "y":
print("-"*50 + "\n" + print_in_blue + "Here is the leaderboard!\n" + print_default + "-"*50)
for c in range(0, len(scoreslist)-1):
max = scoreslist[c]
index_of_max = c
for i in range (c+1, len(scoreslist)):
if (scoreslist[i] > max):
max = scoreslist[i]
index_of_max = i
aux = scoreslist[c]
scoreslist[c] = max
scoreslist[index_of_max] = aux
#print(scoreslist)
print(*scoreslist, sep = "\n")
print("-"*50)
#If they don't want to see scores:
else:
print("OK. Thanks for loging in!")
else:
print(print_in_red + "Incorrect Login credentials, please try again by restarting." + print_default)
#If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
print("Ok, please continue!")
else:
print("This username is already taken. Please try another.")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print("Your passwords do not match. Please try again.")
login_user()

The problem with your code lies in the fact that you are printing the message "Ok, please continue!" within your for loop.
...
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
print("Ok, please continue!")
else:
print("This username is already taken. Please try another.")
...
What happens is that every time your usernameslist[id] is checked against the 'newusername' variable, the print statement 'print("Ok, please continue!")' is run, causing the message to be displayed multiple times.
What you can do to fix this issue is to move the print statement out of the for loop, so that, assuming that a new username does not match any username in the usernameslist, the message "Ok, please continue!" will be displayed once to the user before they are prompted to input their password twice.
Here's what should work for you:
...
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
else:
print("This username is already taken. Please try another.")
if goodlogin2 = True:
print("Ok, please continue!")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
...

It looks like you're iterating over your whole list of usernames and printing out a success or error message with each iteration.
Try this instead:
# If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
if newusername in usernameslist:
print("This username is already taken. Please try another.")
else:
goodlogin2 = True
print("Ok, please continue!")
# for id in range(len(usernameslist)):
# if newusername != usernameslist[id]:
# goodlogin2 = True
# print("Ok, please continue!")
# else:
# print("This username is already taken. Please try another.")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print("Your passwords do not match. Please try again.")
This produces the following output for a user with no previous account who enters a name which has not been used:
--------------------------------------------------
Welcome! Do you have an account (y/n)? n
--------------------------------------------------
What is your new username? not_taken2
Ok, please continue!
What is your new password? pwd2
Please enter your new password again.pwd2
Please follow the instructions to log in with your new credentials.
Please enter your username:

Related

I am writing some code for a login system in python and I can't seem to be able to have it read the email and password from a txt file

import hashlib
def signup():
email = input("Enter an email address: ")
pwd = input("Enter a password: ")
conf_pwd = input("Confirm your password: ")
if conf_pwd == pwd:
enc = conf_pwd.encode()
hash1 = hashlib.sha256(enc).hexdigest()
with open(r'D:\Python Programs\Login\database.txt', "a") as f:
f.write(email + "\n")
f.write(hash1 + "\n")
f.close()
print("You have registered successfully!")
else:
print("Password is not same as above! \nPlease try again")
signup()
def login():
email = input("Enter email: ")
pwd = input("Enter password: ")
auth = pwd.encode()
auth_hash = hashlib.sha256(auth).hexdigest()
with open(r'D:\Python Programs\Login\database.txt', "r") as f:
stored_email, stored_pwd = f.read().split("\n")
f.close()
if email == stored_email and auth_hash == stored_pwd:
print("Logged in Successfully!")
else:
print("Login failed! \nPlease try again")
login()
def welcome():
print("Welcome to the [Insert Game Name Here]")
HaveAccount = input("Have you made an account before? (Y/N): ")
if HaveAccount == ("Y"):
login()
elif HaveAccount == ("N"):
signup()
else:
print("Please enter either 'Y' or 'N'")
welcome()
welcome()
It is specifically line 23 and it has a ValueError: too many values to unpack (expected 2) whenever I try and log in with an email and password. I need to add some extra text in because my post is mostly code and I don't know what else to say so here is some random typing to make more characters in my post. Any help is appreciated. Thanks

Program keeps displaying None even after input

The code is meant to be a simple login code that saves the login information to a .txt file and then when logging in reads the text file to check the user details.
The code runs up until I create an account or try to login and put in my username and password then it comes back with None. I don't understand why it's coming back with None
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
loginexisting()
elif account == "N":
createacc()
else:
print("please type Y or N")
AskAccount()
def loginexisting():
print("Your account already exists, please login\n")
username = input("Please enter your username:")
password = input("Please enter your password:")
f = open('accounts.txt', 'r')
info = f.read()
info = info.split()
if username in info:
index= info.index(username) +1
usr_password = info[index]
if usr_password == password:
return "Welcome Back," + username
else:
return "password entered is wrong"
else:
print("Username is not correct")
print(createacc())
def createacc():
print("Lets create an account for you\n")
username = input("Please input your username:\n")
password = input("please input your password\n")
f = open("accounts.txt",'r')
info = f.read()
if username in info:
return "Name Unavailable. Please Try Again"
f.close()
f = open("accounts.txt",'w')
info = info + " " + username + " " + password
f.write(info)
f.close()
print("Your account details have been saved\n")
print("please login\n")
print(AskAccount())
At the end of your file, you print(AskAccount()). This prints the return value of the function, but AskAccount does not have a return statement, thus it returns None. If you want it to print your desired output, you will need to add return statements.
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
return loginexisting()
elif account == "N":
return createacc()
else:
print("please type Y or N")
return AskAccount()

imbedded if statement not working properly

his is my first time using this website, so i dont know how to use it properly... apologies if its difficult to read.
i have some code to make a login system for my project, and i have used if and else statements to let the user to log in. however, while it works as in there are no error messages its not doing what i would like it to do. when the user login is, it asks them for the username:
username = input("Enter login name: ")
if username in Users:
passw = input("Enter password: ")
if passw in Users:
print ("Login successful!")
however if the username is correct, the program moves onto " passw = input("Enter password: ") " but no matter if the password is correct or not, it goes back to the login menu... im not sure how to fix it.
#full code:
global number
global Users
global username
number = 1
Users = {}
status = ""
def newuser():
global number
print('To create your unique username, please answer these few questions: ')
first = input('Please type your first name: ')
second = input('Please type your surname/last name: ')
year = input('Please type your birth year: ')
part1 = (first[:3])
part2 = (second[:3])
part3 = (year[2:])
username = part1 + part2 + part3
username = str(part1[:3] + part2[:3] + part3[:2] + '' + str(number))
number = number + 1
print('')
print ('here is your unique username: ')
print (username)
print('')
print ('Make sure you know your username for when you login in next time!')
passw = input('please type in your password to login to your account with: ')
Users[username] = passw
print('')
print ('Your account is made! Taking you back to the menu... ')
print('')
def olduser():
global username
global passw
global Users
username = input("Enter login name: ")
if username in Users:
print (Users)
passw = input("Enter password: ")
if passw in Users:
print ("Login successful!")
mainmenu()
else:
print("User doesn't exist!")
def mainmenu():
print('test for main menu is ready')
while status != "q":
status = input("Are you a registered user? y/n? Press q to quit: ")
if status == "n":
newuser()
elif status == "y":
olduser()
else:
print('invalid input try again')

How to format a program so that only username 'admin' can register / add new users in Python?

I had to write a program in python that can add/write 'users' and 'tasks' to a .txt file.
I have done all that and everything works as needed.
I now have to do the following and this is where I'm stuck.
I have to format the program so that:
Only the user with the username 'admin' is allowed to register(make use of the 'r' option) new users.
Note: admin user is saved in users.txt as: admin(username), adm1n(password)
The admin user is provided with a new menu option that allows them to display statistics. When this menu option is selected, the total number of tasks and the total number of users should be displayed in a user-friendly manner.
Here is my code:
users = {}
with open ('user.txt', 'rt')as username:
for line in username:
username, password = line.split(", ")
users[username.strip()] = password.strip() # strip removes leading/trailing whitespaces.
user_username = input("Please enter your username: ")
while user_username not in users:
print("The username is incorrect.")
user_username = input("Please enter a valid username: ")
if user_username in users:
print ("The username is correct.")
with open('user.txt', 'rt') as password:
for line in password:
username, password = line.split(", ")
users[password.strip()] = username.strip() # strip removes leading/trailing whitespaces.
user_password = input("Please enter your password: ")
while user_password not in users:
print("Your username is correct but your password is incorrect.")
user_password = input("Please enter a valid password: ")
if user_password in users:
password2 = ("Your password is correct.")
print (password2)
if password2 == ("Your password is correct."):
# Give the user options to proceed.
user_options = input("""
Please select one of the following options:
r - register a user
a - add a task
va - view all tasks
vm - view my tasks
e - exit
""")
if user_options == "r":
new_user = (input("Please enter a new user name: "))
new_user_password = (input("Please enter a new password: "))
new_password = False
while new_password == False: # Add a 'while loop' untill the condition is met(True).
confirm_new_password = input("Please retype your password to confirm: ")
if new_user_password == confirm_new_password:
new_password = True
elif new_password == False:
print("Your passwords do not match!")
with open ('user.txt', 'a')as user_file:
user_file.write(f"\n{new_user}, {new_user_password}")
# Add a task to a specific user.
elif user_options == "a":
task_file = open("tasks.txt", "a+")
new_task_username = input("Please enter the 'username' of the person this task will be assigned
to: ")
new_task_tile = input("Please enter the 'tile' of the new task: ")
new_task_description = input("Please give a brief description of the new task:\n")
new_task_due_date = input("""Please enter the due date of the given task, in the following
format;
dd-mm-yyyy:\n""")
new_task_completed = input("Is the new task completed (Yes / No): ")
task_file.write(f"\n{new_task_username}, {new_task_tile}, {new_task_description},
{new_task_due_date}, {new_task_completed}")
task_file.close()
# View all tasks.
# NOTE: You have to add tasks first before you can view all tasks.
elif user_options == "va":
task_file = open("tasks.txt", "r")
for line in task_file:
new_task_username, new_task_tile, new_task_description, new_task_due_date, new_task_completed = line.split(", ")
print(f"""
New task username: {new_task_username}
Task tile: {new_task_tile}
Task description: {new_task_description}
Task due date: {new_task_due_date}
Task completion: {new_task_completed}
""")
task_file.close()
# View task assigned to a user.
elif user_options == "vm":
with open("tasks.txt", "r") as task_file:
for line in task_file:
new_task_username, new_task_tile, new_task_description, new_task_due_date,
new_task_completed = line.split(", ")
if user_username == new_task_username:
print(f"""
New task username: {new_task_username}
Task tile: {new_task_tile}
Task description: {new_task_description}
Task due date: {new_task_due_date}
Task completion: {new_task_completed}
""")
elif user_options == "e":
exit
else:
print("Invalid selection! Please choose a valid option.")
This worked for me:
if user_options == "r": # Only the user logged in as 'admin', will be able to access this menu.
if user_username != "admin":
print ("You are not an admin user, only admin can register new users.")
elif user_username == "admin":
# Create a new menu to display for admin.
admin_menu = (input("""
Please select one of the following options:
r - register a new user
d - display statistics = Total number of tasks & users
e - exit
"""))
if admin_menu == "r":
new_user = (input("Please enter a new user name: "))
new_user_password = (input("Please enter a new password: "))
new_password = False
while new_password == False: # Add a 'while loop' untill the condition is met(True).
confirm_new_password = input("Please retype your password to confirm: ")
if new_user_password == confirm_new_password:
new_password = True
elif new_password == False:
print("Your passwords do not match!")
with open ('user.txt', 'a')as user_file:
user_file.write(f"\n{new_user}, {new_user_password}")
elif admin_menu == "d":
# These varibles will only count the lines inside the 'txt' files,
# but since we are storing every new task & user on a new line,
# we can just count the lines for the desired results.
tasks_num = 0
users_num = 0
with open("tasks.txt", "r") as task_file:
for line in task_file:
tasks_num += 1
print (f"\nTotal number of tasks: {tasks_num}")
with open("user.txt", "r") as username:
for line in username:
users_num += 1
print (f"Total number of users: {users_num}")
elif admin_menu == "e":
exit

python read/write to file login script

I was wondering if anyone would help. I am new to python. I am trying to create a basic login script for a game, that will write a username and password to a text file. When logging in, it will read from that text file and compare the entry made by the user. The code is below:
def Register():
print("Hello! You need to register an account before you can begin")
username = input("Please enter a username: ")
password = input("Now please enter a password: ")
file = open("Login.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
print ("Your login details have been saved. ")
print("You will now need to login")
Login()
def Login():
print("Please enter your details to log in")
username1 = input("Please enter your username: ")
password1 = input("Please enter your password: ")
file = open("Login.txt","r")
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
print(username,password)
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
#file.close()
user=input("Are you already a user? ")
if user == "Yes":
Login()
elif user =="No":
Register()
print("Welcome to our game")
I have entered the second user who is stored in the text file, It seems to be working but it checks my first entry and says its incorrect and then loops to the second entry. This is the output I keep getting:
Are you already a user? Yes
Please enter your details to log in
Please enter your username: jen
Please enter your password: ben
tess bess
incorrect
jen ben
Hello jen
Welcome to the dice game
>>>
Does anyone have an idea on how to only display the entry you have entered?
Thanks
Like Sharku said, put the print(username,password) in your if below. Also writting clearly the name and password of the user after he typed it isn"t really a smart moove, delete it and just let your message when a user is logging in !
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
As said by sytech, you could use the break and else clauses of the for loop:
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
break
else:
print("incorrect")
Your 'for loop' will loop through each entry in your file, that means for each entry in the file your for loop prints the entry due to this line:
print(username,password)
If you don't want it to print all values in the file remove this line of code.
Adding a 'break' to your if statement, as suggested by others, will mean that as soon as your loop has found the entry that matches the one entered by the user it will leave the loop and not continue going through all values unnecessarily.
You could do something like this:
if username1 == username and password1 == password:
print("Hello",username)
break
else:
continue
This means that when a user input doesn't match an entry in the file the loop will just continue till it finds a match.
However, your code doesn't take into consideration if a user doesn't exist.
import os.path
if not os.path.exists('register.txt'):
file = open('register.txt', 'w')
file.close()
def register():
username = input('Enter username: ')
if username in open('register.txt', 'r').read():
print('Username already exists')
exit()
password = input('Enter password: ')
c_password = input('Enter confirm password: ')
if password != c_password:
print('Sorry password not match')
exit()
handle = open('register.txt', 'a')
handle.write(username)
handle.write(' ')
handle.write(password)
handle.write('\n')
handle.close()
print('User was successfully registered')
exit()
def login():
username = input('Enter username: ')
password = input('Enter password: ')
get_data = open('register.txt', 'r').readlines()
users_data = []
for user in get_data:
users_data.append(user.split())
total_user = len(users_data)
increment = 0
login_success = 0
while increment < total_user:
usernames = users_data[increment][0]
passwords = users_data[increment][1]
if username == usernames and password == passwords:
login_success = 1
increment += 1
if login_success == 1:
print('Welcome ' + username)
else:
print('invalid username & password')
question = input('Do you have an account?/yes/no')
if question == 'yes':
login()
else:
register()

Categories

Resources