This question already has answers here:
Simple boolean inequality operators mistake
(6 answers)
Closed 4 years ago.
I had previously made a simple logging in code and it was working but when i went to separate data from the code to another .py file and import it, it will not progress passed the "username: " input part (it keeps loading the input for username). Does that mean that the file is not being imported correctly or is it in the main code?
Login.py
print ("Loading please wait...")
import logindata
import inputdata
import time
time.sleep(1.5)
username = ""
while username != logindata.user1 or username != logindata.user2:
print ("Username: ")
username = input()
password = ""
while password != logindata.passw1 or password != logindata.passw2:
print ("password")
password = input()
if username == logindata.user1 and password == logindata.passw1:
print ("Logging in...")
time.sleep(3)
print ("Welcome, user1!")
if username == logindata.user2 and password == logindata.passw2:
print ("Logging in...")
time.sleep(3)
print ("Welcome, user2!")
logindata.py
#Login Data#
user1 = "user1"
passw1 = "pass1"
user2 = "user2"
passw2 = "pass2"
############
It was previously working before i added a second "user" to it.
The issue is in this line:
while username != logindata.user1 or username != logindata.user2:
If user1 and user2 are different, than the condition will always evaluate to false. You'll want to use and rather than or.
Also, you'll probably want to connect the username & password, and not allow user1 to login with the password for user2 and vice versa ...
Change the or to an and.
username = ""
while username != logindata.user1 and username != logindata.user2:
print ("Username: ")
username = input()
password = ""
while password != logindata.passw1 and password != logindata.passw2:
print ("password")
password = input()
When you type in something that matches logindata.user1, user != logindata.user2 evaluates to True and the loop continues. Therefore, you need the username to not match both logindata.user1 and logindata.user2. Same goes for the password.
Related
For some reason the and operator is not functioning properly within the while loop.
When I go to run the code it will exit the loop when either the password or username are matching and not both.
Any help would be great.
root_password = "password123"
root_username = "root"
username = "default"
password = "default"
while username != root_username and password != root_password:
username = input("Username: ")
password = input("Password: ")
if username != root_username and password != root_password:
print("Wrong Credentials")
print("Welcome")
The and operator is exactly doing what it should, it stays in the loop as long as both are not matching.
What you want is continuing loop until both match, so you have to use the OR operator here
This will result in True only when both, username and password don't match. In case the username is correct but password is wrong, False and True = False, and loop will end. What you need is to prompt "Wrong credentials" when either of them is wrong, using OR.
This is a common error while operating on negations or complements. Refer to De-Morgan Laws:
!(username == root_username and password==root_password)
is
username != root_username or password!=root_password
One way to do this is to create a conditional which checks if both the username and password are matching and then put a not in front of that conditional, like this:
not (username == root_username and password == root_password)
This just checks if the user doesn't have a matching username and password, or doesn't have the right credentials.
As Speeeddy has stated, using De-Morgan Laws, this conditional is the same as username != root_username or password != root_password, but this just makes the code easier to read and understand.
Here's the code with this change:
root_password = "password123"
root_username = "root"
username = "default"
password = "default"
while not (username == root_username and password == root_password):
username = input("Username: ")
password = input("Password: ")
if not (username == root_username and password == root_password):
print("Wrong Credentials")
print("Welcome")
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 am trying to make a working user registration program. When asked for the username, the system will look to see if the text entered has already been stored. If the username has already been stored, it will ask for the password for that user. However, if the username has not been stored, it will ask for a password. When these are entered, the script will then appendix onto a .txt of a .py file to make an new account. After the account has been made, the script can then read the .txt or .py file for the login information. My current login code:
loop = "true"
while(loop == "true"):
username = input("Enter Username: ")
password = input("Enter Password: ")
h = input ("Do You Need Help [Y/N]: ")
if(h == "Y" or h == "y" or h == "yes" or h == "Yes"):
print ("Enter username and password to login. If you do not have an account yet, enter 'Guest' as the username and press enter when it asks for the password.")
elif(h == "N" or h == "n" or h == "no" or h == "No"):
print (" >> ")
if(username == "Hello World" and password == "Hello World" or username == "Test User" and password == "Test User" or username == "Guest"):
print ("Logged in Successfully as " + username)
if(username == "Guest"):
print ("Account Status: Online | Guest User")
if not (username == "Guest"):
print ("Account Status: Online | Standard User")
How do you make a database that python can read from for the username and password? Also, how do you make it so that python can appendix to the database to add more usernames and passwords?
This is Python v3.3.0 Mac OSX 10.8
Thank you in advance!
Try using the pickle module:
>>> import pickle
>>> myusername = "Hello"
>>> mypassword = "World"
>>> login = [myusername, mypassword]
>>> pickle.dump(login, open("%s.p" % login[0], "wb")) #Saves credentials in Hello.p, because Hello is the username
>>> #Exit
Now to get it back
>>> import pickle
>>> try:
... password = pickle.load(open("Hello.p", "rb"))[1]
... username = pickle.load(open("Hello.p", "rb"))[0]
... except IndexError: #Sees if the password is not there
... print("There is no information for those credentials")
...
>>> password
'mypassword'
>>> username
'myusername'
If there is no password or username, it prints There is no information for those credentials... Hope this helps!
AND JUST A TIP: don't bother going through if(h == 'n'..., just do a h.lower().startswith("n") == True. .lower() makes everything lowercase, and str.startswith("n") checks if str starts with the letter n.
I'm trying to build a simple login and password application using a dictionary. It works fine except the part where it checks if the login matches the password (in the bottom where it says "Login successful!").
If I were to create login 'a' and password 'b', and then create login 'b' and password 'a', it would log me in if I tried to log in with login 'a' and password 'a'. It just checks if those characters exist somewhere in the dictionary, but not if they are a pair.
Any suggestions how to fix this?
users = {}
status = ""
while status != "q":
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "n": #create new login
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exist in the dictionary
print "Login name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
elif status == "y": #login the user
login = raw_input("Enter login name: ")
if login in users:
passw = raw_input("Enter password: ")
print
if login in users and passw in users: # login matches password
print "Login successful!\n"
else:
print
print("User doesn't exist!\n")
Edit
Now that this is working, I'm trying to divide the application to three functions, for readability purposes. It works, except that I get infinite loop.
Any suggestions why?
users = {}
status = ""
def displayMenu():
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "y":
oldUser()
elif status == "n":
newUser()
def newUser():
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exists
print "\nLogin name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
def oldUser():
login = raw_input("Enter login name: ")
passw = raw_input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
print "\nLogin successful!\n"
else:
print "\nUser doesn't exist or wrong password!\n"
while status != "q":
displayMenu()
Right now you are checking if the given password, passw, matches any keys in users (not right). You need to see if the password entered matches that particular user's password. Since you have already checked if the username exists in the dictionary's keys you don't have to check again, so try something like:
if passw == users[login]:
print "Login successful!\n"
EDIT:
For your updated code, I'm going to assume by "infinite loop" you mean that you cannot use q to exit the program. It's because when you're inside displayMenu, you save user input in a local variable named status. This local variable does not refer to the same status where you are checking,
while status != "q":
In other words, you are using the variable status in two different scopes (changing the inner scope does not change the outer).
There are many ways to fix this, one of which would be changing,
while status != "q":
status = displayMenu()
And adding a return statement at the end of displayMenu like so,
return status
By doing this, you are saving the new value of status from local scope of displayMenu to global scope of your script so that the while loop can work properly.
Another way would be to add this line to the beginning of displayMenu,
global status
This tells Python that status within displayMenu refers to the global scoped status variable and not a new local scoped one.
change
if login in users and passw in users: # login matches password
to
if users[login] == passw: # login matches password
Besides, you should not tell the hackers that "User doesn't exist!". A better solution is to tell a generall reason like: "User doesn't exist or password error!"
Please encrypt you passwords in database if you go put this online.
Good work.
import md5
import sys
# i already made an md5 hash of the password: PASSWORD
password = "319f4d26e3c536b5dd871bb2c52e3178"
def checkPassword():
for key in range(3):
#get the key
p = raw_input("Enter the password >>")
#make an md5 object
mdpass = md5.new(p)
#hexdigest returns a string of the encrypted password
if mdpass.hexdigest() == password:
#password correct
return True
else:
print 'wrong password, try again'
print 'you have failed'
return False
def main():
if checkPassword():
print "Your in"
#continue to do stuff
else:
sys.exit()
if __name__ == '__main__':
main()
usrname = raw_input('username : ')
if usrname == 'username' :
print 'Now type password '
else :
print 'please try another user name .this user name is incorrect'
pasword = raw_input ('password : ')
if pasword == 'password' :
print ' accesses granted '
print ' accesses granted '
print ' accesses granted '
print ' accesses granted '
print 'this service is temporarily unavailable'
else :
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
exit()
This is a very simple one based on the one earlier for a single user with improved grammar and bug fixes:
print("Steam Security Software ©")
print("-------------------------")
print("<<<<<<<<<Welcome>>>>>>>>>")
username = input("Username:")
if username == "username" :
print ("Now type password")
else :
print ("please try another user name. This user name is incorrect")
password = input ("Password:")
if password == "password" :
print ("ACCESS GRANTED")
print ("<<Welcome Admin>>")
#continue for thins like opening webpages or hidden files for access
else :
print ("INTRUDER ALERT !!!!" , "SYSTEM LOCKED")
exit()