I'm not sure why this code isn't working. I have the error TypeError: 'int' object is not iterable I need the code to check the usernames and passwords from two different lists, and if the username and password match spots in the list and are correct, the user is "granted access."
#Part 1: Opening the files and grabbing data
filename1 = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt"
file = open(filename1, "r")
#Usernames
users = file.read()
usernameslist = [line.strip() for line in open("c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt")]
print(users) #Check file
print(usernameslist) #Check usernames list
filename2 = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt"
file = open(filename2, "r")
#Passwords
passwords = file.read()
passwordslist = [line.strip() for line in open("c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt")]
print(passwords) #Check file
print(passwordslist) #Check passwords list
#Compile the usernames and passwords lists for easy checking
compiled_list = list(zip(usernameslist,passwordslist))
print(compiled_list)
#Scores
filename3 = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt"
file = open(filename3, "r")
scores = file.read()
scoreslist = [line.strip() for line in open("c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt")]
print(scores) #Check file
print(scoreslist) #Check scores
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in range(len(usernameslist)):
if username == i and password == [i]:
print("Access granted!")
else:
print("Incorrect Login credentials, please try again.")
login()
The problem is in login(), you are using i as an iterator within itself.
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in [usernameslist]:
if username == [i]:
for j in [passwordslist]:
if password == [j]:
return "Access granted!"
else:
return "Incorrect Login credentials, please try again."
else:
return "Incorrect Login credentials, please try again."
This above should find the password and work with your logic.
However, shouldn't you be using the specific username for the password? This is checking if the username and the password are available, not whether the password matches the username. As you are looping through password and username separately, you would simply check if someone has the password and someone has the username, whether it is the same person or not. If so, replace with this:
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in range(len(usernameslist)):
if username == i and password == j:
return "Access granted!"
else:
return "Incorrect Login credentials, please try again."
Make sure with this that the usernames and passwords are ordered the same within both lists. Or, I'd recommend storing a 2D list looking something like this:
list = [["Annie","password1"],["bob","wordpass39"]] where the first entry is the username and second is the password.
Edit: with the fixed login() function you should now do this:
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in range(len(usernameslist)):
if username == i and password == i:
print("Access granted!")
else:
print("Incorrect Login credentials, please try again.")
Related
I'm trying to create a simple new user registration function. There should be a process for assessing new usernames entered by the user which checks for duplicates in an external file and rejects them. The file user.txt is simply a line-by-line list of usernames and passwords separated by a comma.
Problem: the code keeps ignoring my effort to match each new user input variable user with the usernames stored in the text file (line[0])
The contents of "user.txt" is as follows:
admin, admin
admin1, admin1
admin2, admin2
etc.
Any help appreciated thanks
def reg_user():
if username == "admin" and login == True:
registry = open("user.txt", "r+")
# Requests username and prevents duplicates
for line in registry:
line = line.split(", ")
while registry:
user = input("Please enter a username to register:\n")
if user == line[0]:
print("Sorry, that username is taken. Try a different one.")
password = input("Please enter a password to register:\n")
passcheck = input("Please re-enter your password:\n")
if password != passcheck:
print("Your password doesn't match. Please re-enter your password.")
else:
print("Thanks. You're registered")
user = registry.write("\n" + user + ", " + password)
registry.close()
Something like this should work:
username = 'admin'
login = True
if username == "admin" and login == True:
file = open("user.txt", "r+")
registry = file.read().split('\n')
# Requests username and prevents duplicates
ok = False
while not ok:
user = input("Please enter a username to register:\n")
ok = True
for line in registry:
if user == line.split(', ')[0]:
print("Sorry, that username is taken. Try a different one.")
ok = False
password = input("Please enter a password to register:\n")
passcheck = input("Please re-enter your password:\n")
if password != passcheck:
print("Your password doesn't match. Please re-enter your password.")
else:
print("Thanks. You're registered")
user = file.write("\n" + user + ", " + password)
file.close()
user.txt file:
a, foo
e, pass
Example interaction:
Please enter a username to register:
a
Sorry, that username is taken. Try a different one.
Please enter a username to register:
e
Sorry, that username is taken. Try a different one.
Please enter a username to register:
f
Please enter a password to register:
pass1
Please re-enter your password:
pass1
Thanks. You're registered
I am currently creating a program that creates a login page and asks for a username and password. Then user inputs the username and password and if it is from the data file, it logs you in. Whenever I input the first two users, it says the users do not exist even though they do. When I input the 3rd or 4th user, It works. please Help.
admins.txt =
User1, 24680
User2, 13579
User3, 56789
print("1. Administrator Log-In Portal")
print("2. Make a Reservation")
print("3. Close Application")
choice = int(input("What would you like to do?"))
if (choice == 1):
file = open("admins.txt", "r")
print("Administrator Login Portal")
print("--------------------------")
username = input("Enter Username:")
password = input("Enter Password:")
for line in file:
a,b = line.split(",")
b = b.strip( )
if(a == username and b == password):
print("Login Successful!")
else:
print("Wrong username/password")
file.close( )
Because you're looping over the items and storing the last passworld/username in the variables a and b, only the last user will work.
I recommend using a dictionary to store the usernames and passwords.
file = open("admins.txt", "r")
print("Administrator Login Portal")
print("--------------------------")
username = input("Enter Username:")
password = input("Enter Password:")
login_info = {}
for line in file:
name, password = line.split(",")
password = password.strip()
login_info[name] = password
if username in login_info.keys():
if(login_info[name] == password):
print("Login Successful!")
else:
print("Wrong password")
file.close()
else:
print("Wrong username")
file.close()
the issue is my method of checking the external file isn't working. pretty much all of this isn't working, its just a part of my game.
file = open("users.txt","w")
file.write("ali/n")
file.write("mike/n")
file.write("guy/n")
file.close()
def login():
username = input ("enter username")
**for line in open("users.txt","r").readlines():
while username not in users.txt:**
print("incorrect")
username = input ("enter username ")
print ("correct")
You can try this:
def login():
username = input ("enter username")
users = open("users.txt","r").readlines()
users = [x.rstrip('\n') for x in users] # remove newline for each user in users
while username not in users: # check if entered username is in text file
print("incorrect")
username = input ("enter username ")
print("correct")
Try this
def login():
username = input("enter username ")
users = [x.strip() for x in open("users.txt","r").readlines()]
while username not in users:
print("incorrect")
username = input("enter username ")
print ("correct 1")
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()
I need to check that the usernames and passwords match up with the details in a text file. I'm not sure how to do this. Here is what i have so far (saving the username to the file).
print("Are you a returning player?")
user = input()
if user.lower() == "no":
username = input("Please enter a username for your account.\n")
password = input("Please enter a password for your account.\n")
file = open("account.txt","a")
file.write(username)
file.write("\n")
file.write(password)
file.close()
else:
user_name = input("Please enter your username.\n")
pass_word = input("Please enter your password.\n")
There is another method using with open that close your file after the procedures are done inside the loop, so you can create a read loop and an append loop. For this I like the idea of storing the name and password on the same line, that way we can check to make sure the name and corresponding password are linked to each other rather than being able to use any password for any name. Also when using append we are going to have to add a '\n' or everything we write will be written to the same line
To verify the user we open the file as r and then we can use for line in f to get all the lines in the .txt from there we can loop through each line and if both username and password exist in the same line, we can welcome the user, if not send them back to the beginning.
Hope this helps!
while True:
user = input('\nAre you a returning player: ')
if user.lower() == 'no':
with open('accounts.txt', 'a') as f:
username = input('\nEnter username: ')
password = input('Enter password: ')
combo = username + ' ' + password
f.write(combo + '\n')
else:
with open('accounts.txt', 'r') as f:
username = input('\nEnter username: ')
password = input('Enter password: ')
for line in f:
if username + ' ' + password + '\n' == line:
print('Welcome')
break
else:
print('Username and/or Password Incorrect')
Are you a returning player: no
Enter username: vash
Enter password: stampede
Are you a returning player: yes
Enter username: vash
Enter password: stacko
Username and/or Password Incorrect
Are you a returning player: yes
Enter username: vash
Enter password: stampede
Welcome