I'm trying to practice my python skills, I knew that I was kind of unfamiliar with how to work with files so I decided to teach my self. The code is basically making an account, signing in and checking the user and pass stored in a file. I know my user and pass is appending and reading to the file. The problem i'm getting is in my if statement. I'm using if i == user but == means literal. So i tried just using one = to check if one variable = the variable that the user has put in, when I do that, I get a syntax error. My last question is when I run the code, in they else statement where it says username incorrect, it says it 2 or 3 times in the console. This confuses me because no where outside of the else statement is their a while or for loop. If someone can just explain how to get my if statment to excutute when the user and password string are right. That would be great. Also if you know why my console is doing the else: print('username incorrect) 3 times for no reason. I'm very curious to know
I tried printing out the variables in my for loop and it indeed printed the strings in the file.
u = open('users.txt', 'a+')
p = open('pass.txt', 'a+')
does_acc = input('Do you have a account? ')
if does_acc == 'no' or does_acc == 'No':
new_user = input('Username: ')
u.write(new_user + '\n')
new_pass = input('Password: ')
p.write(new_pass + '\n')
sign_in = input('Would you like to sign in? ')
if sign_in == 'yes' or sign_in == 'Yes':
n = open('users.txt', 'r')
m = open('pass.txt', 'r')
lines = n.readlines()
line = m.readlines()
user = input('Username: ')
for i in lines:
print(i)
if i = user:
password = input('Password: ')
for x in lines:
if password == x:
print('secret file opened')
else:
print("{} is not a valid password.").format(password)
else:
print('Username incorrect.')
else:
print('Have a nice day.')
u.close()
p.close()
Do you have a account? yes
Would you like to sign in? yes
Bob
Username: Bob
Username incorrect.
Username incorrect.
This if i = user: should be replaced with this: if i == user: (double equal sign)
Once you have created a new account, you should close the files, because you're going to open them again while they are already open. This might or might not lead to a wrongfully read / written data.
The idea that once user has entered their name, the whole password file is matched against the input password does not seem right -- you only need to check the one password for every user.
for x in lines: tries to match the password against the user names. Seems strange.
print("{} is not a valid password.").format(password) has wrong parenthesis order, it should be "string".format(parm) enclosed in print( .... ), not vice versa.
All in all, I'd rather rewrite your password matching part like this:
with open( 'passwords.txt' ) as fin :
passwords = [p.strip() for p in fin.readlines()]
with open( 'users.txt' ) as fin :
users = [u.strip() for u in fin.readlines()]
user = input( 'User: ' )
password = input( 'Password: ' )
if [user, password] in zip( users, passwords ) :
print( "You're welcome!" )
else :
print( "Go away!" )
Or something along the lines.
the if i = user should be if i == user and also you are opening the same file twice, one at the beginning and the second one after if sign_in == 'yes' or sign_in == 'Yes':
Related
I started learning python(and coding in general) a couple of weeks ago and I am having struggle in a project I trying to make. In part of the project I am trying to make a register and login system, everything went fine expect the 'username already taken' part in the register section.
No matter what I do, the code just keep allowing registering even if the username already taken(You can register with "x" username, and right after registering again with "x" username).
I will appreciate any kind of help!(and sorry for the english :) )
import re
Users = open('Users.txt', mode = 'a')
Hquestion = input("\t\t If you already registered please press Y, if you need to register
please press N")
def register():
if Hquestion == "N" or Hquestion == "n":
with open('Logindata.txt', mode = 'a') as logindata:
firstname = input('please write your first name(only a-zA-Z allowed): ')
username = input('Enter Username : ')
with open('Users.txt', mode = 'r') as userdata:
if username in userdata:
print("username already taken!")
return register()
password = input ('Enter Password (using only a-zA-Z0-9!##$%^&*. min 8 characters) : ' )
passpattern = re.compile('[a-zA-Z0-9##$%^&*()-+=?/".,{}\;:~]{8,}')
namepattern = re.findall('[0-9!##$%^&*()-+=?/".,{}\;:~]',firstname)
while not passpattern.match(password):
print("Your password is invalid. Please make sure you password is atleast 8 characters long!\n")
return register()
if namepattern:
print("Please use only a-z A-Z characters for first and last name!\n")
return register()
Users.write(f'{username}\n')
Users.close()
logindata.write(f'{username} ')
logindata.write(f'{password} ')
logindata.write(f'{firstname}\n')
def login():
if Hquestion == "Y" or Hqeustion == "y":
loginuser = input('Write your username: ')
loginpass = input('Write your password: ')
for user_pass in open('Logindata.txt', mode = 'r').readlines():
loginsplit = user_pass.split()
if loginuser == loginsplit[0] and loginpass == loginsplit[1]:
print("You have succsesfuly loged in! Enjoy shoping in Tomer's Shop!")
return
else:
print("Your username or password wrong, please try again")
return login()
register()
login()
From Membership test operations, python will iterate containers that do not implement __contains__. The file object is one of those containers.
That means that your membership test if username in userdata: will iterate the file line by line until username is found. The thing is, that's the full line, including newline. A quick test shows that username without newline is False and reads through the entire file
>>> # create test file
>>> open("users.txt", "w").write("Alice\nBob\nChuck\n")
16
>>> username = "Bob"
>>> f = open("users.txt")
>>> username in f
False
>>> f.read()
''
But adding the newline fixes the problem
>>> f = open("users.txt")
>>> username + "\n" in f
True
>>> f.read()
'Chuck\n'
I'm trying to get my code to check if a word is already in the document. However when choosing a variable (username) that happens to share the same letters going to the right as the preexisting one in the file, it thinks that the name is taken. For example, if abcdefg was in the file, if I was to right defg or fg or g, it would think the username was taken.
def register():
print("━━━━ACCOUNT CREATION━━━━")
username = input("Create Username: ")
with open("Login.txt", "r") as loginfile:
if (username+",") in loginfile.read():
print("Sorry, but that username is taken.")
choice = input("Try again with a new name? (Y/N)")
choice = choice.upper()
My case:
Say I had the name, Joe which is already in the file. If I tried to make a username that is just e, then it would think it is Joe, as it is looking for the e, next to a comma.
Anyway to fix this? Thanks!
This should work
with open('login.txt', 'r') as LoginFile:
# the split function splits a string to a list on mark
Data = LoginFile.read().split(" ,")
if username in Data:
# .....
if this isn't what you want try this built-in module :
https://docs.python.org/3/library/re.html
def register():
print("━━━━ACCOUNT CREATION━━━━")
# read the names from the file
with open('Login.txt', 'r') as f:
names = f.read().split(',')
username = input("Create Username: ")
for name in names:
# check if any names end with this name have been created
if name.endswith(username):
# found
print("Sorry, but that username is taken.")
# we want to keep ask the user to select if
# they enter something other than Y/N
while True:
# ask for the option
option = input("Try again with a new name? (Y/N) ")
# try again, we just rerun this function
if option == 'Y':
register()
# don't ask any more
break
elif option == 'N':
# exit if user chooses N
break
# if the user chooses something else, continue
# the loop and keep asking
# if no names end with username, goto else
break
else:
# name available, save it to the file
print("Name created successfully:", username)
new_names = names + [username]
with open('Login.txt', 'w') as f:
f.write(','.join(new_names))
I have tested it, please try and see if it works for you.
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 function for client registration where the client's username must be unique. I made a dict and a list where I put everything from my txt file, and now I've been trying to set for and while loops, but it isn't going well:
client_list = []
def c_l():
with open("svi.txt","r") as f:
pieces = ["username","password","name","lastname","role"]
for r in f.readlines():
dicct = {}
bla = r.strip().split("|")
count = 0
for i in bla:
dicct[pieces[count]] = i
count += 1
client_list.append(dicct)
c_l()
def reg():
for r in client_list:
while True:
username = input("Username: ")
if (username == r["username"] ):
print("Username is already taken, please try again: ")
else:
break
password = input("Your password:")
name = input("Your name: ")
lastname = input("Your lastname: ")
client = username + "|" + password + "|" + name + "|" + lastname + "|" + "buyer"
with open("svi.txt","a") as f:
f.write(client)
reg()
When I was typing this function for the first time, I made all in one function, where I opened the file, typed code for unique username and then printed client into that txt file. In that function my while loop worked, because all I had to do is to split the parts of the file and index the right one, then make this while loop, which worked fine. But now I've been told that I have to do it by using dict and list and I tried doing this, I don't know what the problem is with my approach.
You may want to load usernames into a set which ensures uniqueness. Then, in your reg function check whether the new username is in the set, like:
if username in myset:
raise InvalidUsernameError
else:
myset.add(username)