I have a log in system for two users. I had duplicate code for it but I made it a function to make the code more efficient. However, I am not too sure how to make some variables change for each user. Here is the code:
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
username=input("What is your username: ")
password=input("What is your password: ")
break
else:
print("Invalid input.")
continue
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
Basically, I want to have username and password different for user 1 to user 2 but I have no idea where to start and nothing seems to help. When I input the username and password for user two, it overwrites the input I made for user one and I don't want that happening. Thanks,
Dylan
It seems you are practicing python or a simple question, well I have added the Pseudo code which you can develop yourself because it is simple and if you write this yourself it will help you think in that paradigm inorder to solve this problem.
Whenever you want to do something or implement it, do it in steps or write it down, it helps alot.
Read this btw.
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
username=input("What is your username: ")
password=input("What is your password: ")
#How to Save Username and password
#1. Find Two Empty Rows or one empty row and it's corresponding column in CSV file. (Can be done using running a loop on the csv file)
#2. Store Username password in the corresponding rows and columns above.
break
else:
print("Invalid input.")
continue
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
As per your requirements it seems that dictionary of successfully logged in usernames and passwords could be better for you if you store them
Make your code as belows.
users_logged_in={}
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
# usernames and passwords you have entered stored in dict
users_logged_in[username]=password
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
username=input("What is your username: ")
password=input("What is your password: ")
break
else:
print("Invalid input.")
continue
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
If you want the order of the usernames logged in to system to be preserved go to OrderedDict from Python collections.
Else you could create list with tuples of usernames and passwords
Create tuple as below in above code
logged_user_details=(username,passowrd)
and let
users_logged_in
be a list of usernames and passwords, Append to it the tuple created above.
users_logged_in.append(logged_user_details).
Now you would have users and passwords in your list as shown below and order of your entry will also be preserved.
[(User1,Password1),(User2,Password2),(User3,Password3)].
It is entirely dependent on your usage purpose of storing username and password whether you go with List or Dict approach.
Related
I made a program that allows the user to create an account. It seemed to work until I tried the login feature, which kept alerting me that the username and password do not exist. When I re-run the program and create an account, the txt file has my given name and password inside. However when I close the program and reopen it to run the login feature the name and password are no longer there. Any ideas on how to fix this?
PS: I'm rather new to all of this and if there is anything i could/should have done instead please let me know.
while True:
#Account file and same file as list.
AccountsFile = open("AccountProj.txt", "w+")
AccountList = [line.split(',') for line in AccountsFile.readlines()]
#Creates an account
def createaccount():
while True:
newname = (input("Please create a username: "))
if newname in AccountsFile:
print("Username already in use.")
continue
elif newname not in AccountsFile:
newpassword = input("Please create a password: ")
checkpassword = input("Re-enter password: ")
if checkpassword == newpassword:
print("Account Sucessesfuly created!")
AccountsFile.write(newname + "\n")
AccountsFile.write(checkpassword + "\n")
AccountsFile.close()
break
elif checkpassword != newpassword:
print("Passwords do not match")
continue
#Logs into an account
def loginaccount():
while True:
username_entry = input("Enter username: ")
if username_entry not in AccountList:
print("Username not found. Please enter a valid name")
continue
elif username_entry in AccountList:
password_entry = input("Enter password: ")
if password_entry in AccountList[AccountList.index(username_entry) + 1]:
print("Login sucessful!")
AccountsFile.close()
break
if password_entry not in AccountList[AccountList.index(username_entry) + 1]:
print("Username and password do not match. Please try again.")
AccountsFile.close()
continue
#Asks if user wants to create or login to an account
loginchoice = input("Would you like to login? (Y/N) ")
if loginchoice in ('Y', 'N'):
if loginchoice == 'Y':
loginaccount()
if loginchoice == 'N':
createchoice = str(input("Would you like to create an account? (Y/N) "))
if createchoice in ('Y', 'N'):
if createchoice == 'Y':
createaccount()
if createchoice == 'N':
exit()
break
else:
print("Invalid Input")
You opened your file in w+ mode, this will override your previous content because it starts writing right at the beginning of the file.
Instead, you should use the a mode for appending your text to any previously written content.
See: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files:
(...) mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end.
The login system i have wont break out of the loop. I have shown this to my CS teacher and he told me to change the indentations of the break. It didn't work. I have been looking around but I can't seem to find a reason as of why the loop wont break. Here is the code:
while True:
print("User 1")
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1:
if row[1]==password1:
print("Welcome " + username1)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
The code asks if the user has an account. When I input yes and give valid username and password, it continues with the loop. For context when the user logins in, it says welcome and breaks out of the loop. However this isn't happening, it is instead saying welcome and restarting the loop. The csv for this contains the login details.
Any help as of why the loop wont break will be greatly appreciated.
Dylan
Something like this? I mean you already have a "loggedin" variable, why not use it in the while loop...
loggedin = False
while not loggedin:
print("User 1")
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1 and row[1]==password1:
print("Welcome " + username1)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
You are missing a break.
You break out of the for loop, but never the while loop.
Try this:
while True:
print("User 1")
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1:
if row[1]==password1:
print("Welcome " + username1)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
if loggedin==True:
break
EDIT:
Personally, i would avoid using a while True and instead do something like this:
loggedin = False
while not loggedin:
print("User 1") # Consider moving this outside of the while loop too
login=input("Do you have an account? (yes/no) ")
if login.lower() == "yes":
login1=open("login.csv") # Consider moving this outside of the while loop too
reader = csv.reader(login1) # Consider moving this outside of the while loop too
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1 and row[1]==password1:
print("Welcome " + username1)
loggedin = True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
Note here that the continue is not needed.
I have a code that writes usernames, passwords and scores into a csv file in the format: username, password, score. I have it so it writes the username and password at the beginning of the code:
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
loggedin=True
login=open("login.csv","a")
login.write(username + "," + password + "\n")
login.close()
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
I do this for user one and user 2.
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
In the code, this puts the usernames and passwords into column 0 and 1.
Then at the end after the game, it writes the score into the csv file. The part i'm struggling with is then writing the score into column 2. I need it to write on the next available cell in the csv file in row 2.
Any help on this would be greatly appreciated.
Dylan
If I correctly interpreted your request, you simply have to modify this line:
login.write(username + "," + password + "\n")
with
login.write(username + "," + password + ",")
and then add the score with the line terminator '\n'.
In this way you'll get:
username,password,score
all in the same line.
I rewrote your code, so it's readable:
def login_system():
loggedin = False
with open("login.csv", newline='') as fid:
reader = csv.reader(fid, delimiter=",")
login = list(reader)
while not loggedin:
ans=input("Do you have an account? (yes/no) ")
if ans.lower()=="yes":
username=input("What is your username: ")
password=input("What is your password: ")
if [username, password] in login:
print("Welcome " + username)
loggedin=True
return loggedin
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif ans.lower() == "no":
username=input("New username: ")
password=input("New password: ")
with open("login.csv", "a") as login:
login.write(username+","+password+"\n")
print("Welcome "+username)
loggedin = True
return loggedin
don't give two variables the same name
use the with statement for file handling
don't open and close the same file hundreds of times, when you only need to do so once
Lastly to your actual question:
It's way easier just writing a new file or overwriting the old one. And also faster.
I have two while loops that are almost identical apart from a few numbers have changed. I've been looking around but I can't find a solution to my problem. Any help would be appreciated. I want to make the two while loops one loop but I dont know how. I've been looking around for an answer but nothing seems to apply to my problem.
while True:
print("User 1")
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1:
if row[1]==password1:
print("Welcome " + username1)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
username1=input("What is your username: ")
password1=input("What is your password: ")
break
else:
print("Invalid input.")
continue
The only thing that has changed is the number 1 has changed to a number 2 (with the exception of row[1])
Again, any help would be appreciated.
From you saying the only difference is 1 becomes 2 I'm guessing you are just trying to run the loop again for a second user, perhaps a dictionary here, then you could just iterate the loop you already have constructed for each user in the dicitonary, you would have to touch up your loops I cannot run them but an idea for format would be something like so
while True:
users = {'User 1': [username1, password1], 'User 2': [username2, password2]}
for k in users:
print('{}'.format(k))
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
users[k][0]=input("What is your username: ")
users[k][1]=input("What is your password: ")
for row in reader:
if row[0]==users[k][0]:
if row[1]==users[k][1]:
print("Welcome " + users[k][0])
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
users[k][0]=input("What is your username: ")
users[k][1]=input("What is your password: ")
break
else:
print("Invalid input.")
continue
Assuming your while loops are within the functions you listed, this is the easiest way I can think of.
from threading import Thread
t1 = Thread(target = firstFunction)
t2 = Thread(target = secondFunction)
t1.start()
t2.start()
I'm making login/signing section for my code. I have 2 issues with it. I need help:
First question Yes or No functions well until other character entered. While loop is not accepted for some reason. How to get back to beginning until Y or N entered?
I would like to store dict with usernames and passwords as CSV file sorted in two columns not rows. How to do it.
Thanks
Here is the code....
# CREATING START DICTIONARY
users = {"guest": "guestpass", "admin": "adpass"}
status = input("\rAre you a registered user? Y / N? ").upper()
while status != "Y" and status != "N":
print ("Please enter Y or N")
# NEW USER
if status == "N":
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exist in the dictionary
print("Login name already exist! Please, choose another one.\n")
else:
createPass = input("Create password: ")
retypePass = input("Retype password: ")
while True:
if createPass != retypePass:
print("\nPassword error!\n")
else:
users.update({createLogin : createPass})
print("\nNew user created! Welcome to ARR!\n")
break
import csv
writer = csv.writer(open('UsersFile.csv', 'wb'))
for key, value in users.items():
writer.writerow([createLogin, createPass])
# LOGIN EXISTING/NEW USER
elif status == "Y":
while True:
loginName = input("Enter login name: ").lower()
if loginName not in users:
print("User doesn't exist! Please enter existing name or sign-in.")
print("----------------------------------------------------------")
else:
passw = input("Enter password: ")
# LOGIN MATCHES PASSWORD
if loginName in users and passw != users.get(loginName):
print("Wrong password! Please enter username and password again!")
else:
print("Login successful!\n")
break
1) In your y/n while loop you are missing a tab to indent the print statement.
2) https://docs.python.org/2/library/csv.html
Some issues I see so far:
Indentation. print ("Please enter Y or N") should be indented relative to the while statement on the previous line.
Also, the statement if createLogin in users and the following else statement should probably be indented one more level, if they are meant to be within the if status == 'N' statement.
Import statement. Generally, things like import csv would be at the top of the file. Try moving it there and see if it helps.