Python - unavailable username - python

I am trying to create a small program that registers a user to a text file. It asks the user to create a username and it checks if the chosen username already exists in that text file. If so I need the user to be in loop until they enter a different username. The file contains usernames and passwords for each individual separated by ", " eg. (Sanele, afkojs). Each user is stored in a separate line. My code is not keeping the user in this loop it goes through
cont_ = False
while not cont_ :
new_username = input(" Create a Username: ")
unavail_usernames = file_opener("user_info") *#function that opens the text file*
for names in unavail_usernames:
user_info_list = names.split(", ") *#Every user is stored in a separate line*
if new_username != user_info_list[0]:
cont_ = True
if not cont_:
print("username unavailable, enter a different username")
unavail_usernames.seek(0)

Try this:
l=['a,b,c','d,e,f','g,h,i']
inp = input()
while inp in list(map(lambda x:x.split(',')[0],l)):
print("username unavailable, enter a different username")
inp=input()
print('Username is available')

This code
for names in unavail_usernames:
user_info_list = names.split(", ") *#Every user is stored in a separate line*
if new_username != user_info_list[0]:
cont_ = True
set cont_ to True as soon as different name is found. You are checking: does file hold any username different than given? whilst you should: does all username in file are different from given?

Related

TypeError in simple registration/login program

For practice purposes I tried coding a little registration/login system which stores the registered users' data in a list.
I tried to solve this by getting user input (name, nickname and password), then create a list with the chosen "Name" which then stores "Nickname" and "PW" . This then should be then stored in the created list "users" which is being created in the beginning.
So I would have a list with different names/persons which includes their data.
The problem is that in the else statement it won't let me create the name-variable list with (username, password) in it. "TypeError: string indices must be integers"
users = []
def register():
print("Please insert your Name")
name = input()
print("Please insert your Username")
username = input()
print("Please type your Password")
userpw = input()
if name in users:
print("Account already exist, try again")
register()
else:
users.append(name[username, userpw])
This code creates a dictionary for a user and then check if its already registrated. I recommend using some sort of database to avoid dataloss from program restarts.
users = []
def register():
print("Please insert your Name")
name = input()
print("Please insert your Username")
username = input()
print("Please type your Password")
userpw = input()
for x in users:
if x['name'] == name:
print("Account already exist, try again")
register()
return
user = {'name': name,
'username': username,
'password': userpw}
users.append(user)

How To Slove Error For The Login Code In Python Using CSV File?

This is my code for Verifying User ID and password from a csv file.
CODE
import pandas as pd
login():
df=pd.read_csv("IDPASS.csv")
for i in range(len(df)):
x=input("Enter User Name=")
y=input("ENter The Password=")
if (df.iloc[i]["ID"])==x:
if str(df.iloc[i]["PASS"])==y:
print("Succesfully Logined")
break
else:
print("Invalid Password")
print("Try Again!!")
else:
print("Invalid Username")
print("Try Again!!")
login()
Output1:
Enter User Name=JEET1073
ENter The Password=str1234
Succesfully Logined
Here I have entered correct id password and the code is executed perfectly!!
Output2:
Enter User Name=dw
ENter The Password=wd
Invalid Username
Try Again!!
Enter User Name=JEET1073
ENter The Password=str1234
Invalid Username
Try Again!!
Enter User Name=JEET1073
ENter The Password=str1234
Invalid Username
Try Again!!
Enter User Name=JEET1073
ENter The Password=str1234
Invalid Username
Try Again!!
Enter User Name=JEET1073
ENter The Password=str1234
Invalid Username
Try Again!!
Here at first i have entered wrong id and password and then i was trying to enter the correct id and password but it was showing invalid username. any solutions will be appreciated,also i want a solution in which if a user enters wrong id password the code should run again asking id and password till the user id and password entered is not correct.Thanks in advance.
After the clarification, this should be the functionality you are seeking.
First import pandas and read the csv:
import pandas as pd
df = pd.read_csv("IDPASS.csv")
We will now read the values stored in the csv and store them as a list. A list of users and a list of passwords. A good practice would be to do this outside of any loops.
csv_id_list = df['ID'].to_list()
csv_pass_list = df['PASS'].to_list()
If you don't know how long your loop will have to go on for (we don't know how many times the user will try the password) use a while loop. Initialize the initial state of the correct login variable.
correct_login = False
Now where the magic happens. We will start a while loop. While correct_login is false, we will keep asking the user for their username and password. IF the input by the user matches a list element, get the index for that list element, then start another IF statement. . This will break the while loop. ELSE they get an invalid password message, IF the input matches the list element at the correct index, print correct_msg and correct_login = True. Break while loop. ELSE correct_login is still false, user must try again.
This means that the user must input the correct username and the password it corresponds to, they cannot input the password of another user and log in.
while not correct_login:
x = input("Enter User Name=")
y = input("Enter The Password=")
correct_msg = 'Successfully logged in.'
incorrect_msg = 'Invalid Password.' + '\n' + 'Try Again.'
if x in csv_id_list:
x_index = csv_id_list.index(x)
if y == csv_pass_list[x_index]:
print(correct_msg)
correct_login = True
else:
correct_login = False
print(incorrect_msg)
else:
correct_login = False
print(incorrect_msg)

Is there any easy way to check for duplicates in a text file in Python?

There's one last feature I want for my bank account system.
I want it to check if a username has already been saved to the text file database. If the username already exists, then it should tell the user that they can't have that name option. If not, then they would be able to use it.
The rest of my code works as it should, it's just the fcat that I can't append/update my text file properly and see if usernames already exist in the text file database.
import sys
users = {}
status = ""
# Functions ---------------------------------------------------------------------------------------------------------
# Select either account creation or login
def displayMenu():
global status
status = input("Are you a registered user? \n1 - Yes \n2 - No \nQ - Quit \n")
if status == '1':
oldUser()
elif status == '2':
newUser()
else:
print("Unknown input error, exiting . . . .")
sys.exit(0)
return status
# Account creation
def newUser():
global createLogin
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exists
print ("\nLogin name already exists!\n")
else:
createPassw = input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nAccount created!\n")
#---- Storing the username in a txt file
file = open("accountfile.txt", "a")
file.write(createLogin)
file.write("\n")
file.close()
oldUser()
# Account login
def oldUser():
global login
login = input("Enter login name: ")
passw = input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
file = open("accountfile.txt", "r")
for text in file: ######## This is where I'm trying to compare username duplicates
if text in file == createLogin:
print("Username already exists!")
print("\nLogin successful!\n")
Bank_Account()
else:
print("\nUser doesn't exist or wrong password!\n")
print("Restarting. Please enter details correctly . . . . .")
sys.exit(0)
class Bank_Account:
def __init__(self):
self.balance=0
response = ''
def deposit(self):
try:
amount=float(input("Enter amount to be Deposited: "))
except ValueError:
print("Enter digits only")
else:
self.balance += amount
print("\n Amount Deposited:",amount)
def withdraw(self):
try:
amount = float(input("Enter amount to be Withdrawn: "))
if self.balance>=amount:
self.balance-=amount
print("\n You Withdrew:", amount)
except ValueError:
print("Enter digits only")
s.withdraw()
else:
print("\n ")
def display(self):
print("\n Remaining Balance=",self.balance)
displayMenu()
s = Bank_Account()
# Calling functions with that class object
s.deposit()
s.withdraw()
s.display()
So it looks you are are writing the user input in the file accountfile.txt. So after a few users log in it might look something like:
$ cat accountfile.txt
mike
sarah
morgan
lee
The section of your code in question is here:
file = open("accountfile.txt", "r")
for text in file:
if text in file == createLogin:
print("Username already exists!")
This particular part is probably not doing what you think it's doing:
if text in file == createLogin
...
if text in file is returning either True or False.
...
So the line above is essentially saying
if False == createLogin
or
if True == createLogin
I believe what you want to do is check if a name is in accountfile.txt. The smallest change you could make to your code in order to achieve that would be
file = open("accountfile.txt", "r")
for text in file:
if text.strip() == createLogin: # .strip() will clean up the \n
print("Username already exists!")
This line:
if text in file == createLogin: is where you are making a mistake. The line is essentially saying:
"(if the text is in the file) compare the result of that check with the string createLogin".
i.e. if (True/False) == createLogin, which is always false because the True/False boolean primitives are never equal to any string (if it actually runs, i have not tested to see if an exception will be thrown).
what you should do is this
for text in file: # get one line of text
if createLogin == text.strip(): # compare the line with the user input string
print("Username already exists!")
break
.strip() removes any leading or trailing spaces in the database stored name (in this case the line break character \n used to denote the end of a line in the file. break ends the loop prematurely cos your lookup is complete since you found what you were looking for, and it would be an unnecessary to continue comparing the user input with other strings, imagine the txt had 1000 names and the 1st name was a match, the user would see the error printed but the program would continue running for the rest of the 999 tries, making it seem sluggish and waste unnecessary CPU cycles.
The database is still case sensitive however which may or may not be desired depending on your requirements. For case insensitivity you could do the following:
for text in file: # get one line of text
if createLogin.lower() == text.strip().lower(): # compare the line with the user input string
print("Username already exists!")
break
.lower() makes both strings into lower case strings and then checks if they are the same, eliminating the case sensitivity.
Instead of writing to the text file, try pickling the database.
This will save a representation of the object that you can easily load back into your program.
import pickle
users = {}
users["Ash"] = "password"
pickle.dump(users, open("users.p", "wb"))
loaded_users = pickle.load(open("users.p", "rb"))
print(loaded_users)
A more advanced solution may also be to check out a relational database, such as [sqlite3][1]

How do I loop my password/username login page and read the password/username from an external file?

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

if x in [list] iterator

def new_user() -> str:
users = []
print("Welcome to The 'Create New User' Interface")
sleep(0.5)
x = input("Enter Name to Use for Account Access\n*Name is Case Sensitive to Access Account*: ")
if x in users:
x = input("That User Already Exists! Enter a New Name: ")
users.append(x)
print("Your Account Access Name is: " + str(x))
else:
users.append(x)
print("Your Account Access Name is: " + str(x))
So I'm not sure how to word this question but I have this block of code and as you can see I want to check if the user inputted name already exists, and if it does it'll prompt for a new name and add it to the list, and if it doesn't already exist, it'll add it to the list, but there's a way around this, if the list already contains a name and the user inputs that same name the if x in users: code will run and when prompted to enter another name, if they enter that same name, it wont recognize that it already exists and add it to the list either way, how can i prevent this?
To get valid user input wrap the request in a loop and when you have valid input break out, e.g.:
print("Enter Name to Use for Account Access")
print("*Name is Case Sensitive to Access Account*")
while True:
x = input("Enter a Name: ")
if x not in users: # Valid input
break
print("That User Already Exists!")
users.append(x)
print("Your Account Access Name is:", x)
Solution
users = []
print("Welcome to The 'Create New User' Interface")
x = input("Enter Name to Use for Account Access\n*Name is Case Sensitive to Access Account*: ")
while x in users:
x = input("That User Already Exists! Enter a New Name: ")
users.append(x)
print("Your Account Access Name is: " + str(x))
Simply just changed your if loop to a while loop that will continue until a unique name is given.
Suggestions
users = []
print("Welcome to The 'Create New User' Interface")
while True:
user_name = '' #now users can not enter a empty user_name
while not user_name:
user_name = input("Enter Name to Use for Account Access: ")
for i in range(0, len(users)): #different loop to enable use of lower()
while user_name.lower() == users[i].lower(): #removes need for unique cases
print("That User Already Exists!")
user_name = '' #again stopping empty fields
while not user_name:
user_name = input("Enter Name to Use for Account Access: ")
users.append(user_name)
print("Your Account Access Name is: " + user_name)
For start we can create a loop that will reject any blank user_name.
Next we can use .lower() when checking to see if user_name exists in users[]. By doing this we can preserve the unique case format the user wants to use to store their name(perhaps for display purposes) but at the same time we can check to see if user_name already exists regardless of case format.
Cleaning it up we can go with something like this:
def ask_user(message=''): #create function to check for blank inputs
user_name = ''
while not user_name:
user_name = input(message)
return user_name
users = []
print("Welcome to The 'Create New User' Interface")
while True:
user_name = ask_user("Enter Name to Use for Account Access: ")
for i in range(0, len(users)):
while user_name.lower() == users[i].lower():
print("\nThat User Already Exists!") #newline for clarity
user_name = ask_user("Enter Name to Use for Account Access: ")
users.append(user_name)
print("\nYour Account Access Name is: " + user_name) #newline for clarity
Here I created ask_user which handles blank inputs. Then added a \n in a few spots to help with readability.
Output
(xenial)vash#localhost:~/pcc/10$ python3 helping.py
Welcome to The 'Create New User' Interface
Enter Name to Use for Account Access:
Enter Name to Use for Account Access: vash
Your Account Access Name is: vash
Enter Name to Use for Account Access: VASH
That User Already Exists!
Enter Name to Use for Account Access:
Enter Name to Use for Account Access: p0seidon
Your Account Access Name is: p0seidon
Enter Name to Use for Account Access: P0SEidoN
That User Already Exists!
Hope this helps!

Categories

Resources