Python - 'And' operator not functioning properly - python

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")

Related

Password keeper program does not merge dictionaries as intended

I need help with some code id been writing randomly about a passwor keeper
I'd appreciate it so much if the help is beginner friendly.
I tried searching for some ways to merge dicts and the entire app isn't working.
User_password_dict = {" " : " "}
def merge_lists(username, password):
dict_append = {}
dict_append[username] = password
User_password_dict.update
def user_info_collection():
while True:
username = input (f"What is would you like your'e username to be ?\n\t:")
if username in User_password_dict:
print ("you need to change your'e username")
break
else:
password = input(f"Type a password\n\t:")
password_check = input(f"Type your password again \n\t: ")
if password_check != password:
print("you have not input the correct password")
break
else:
User_info = merge_lists(username, password)
return User_info
user_info_collection()
print(User_password_dict)
Okay, so you made a good effort but overcomplicated the dict part.
The merge_lists function is not needed as appending a dict is much simpler than that !!
The key line of code that i added was this:
user_password_dict[username] = password
and i removed a couple of unnecessary parts.
So, this will work:
user_password_dict = {}
def user_info_collection():
while True:
username = input (f"What is would you like your'e username to be ?\n\t:")
if username in user_password_dict:
print ("you need to change your'e username")
break
else:
password = input(f"Type a password\n\t:")
password_check = input(f"Type your password again \n\t: ")
if password_check != password:
print("you have not input the correct password")
break
else:
user_password_dict[username] = password
return
user_info_collection()
print(user_password_dict)
here is the result:
What is would you like your'e username to be ?
:test
Type a password
:blah
Type your password again
: blah
{'test': 'blah'}

How do I check if two input variables are in the same position in two different lists and return as valid?

I'm trying to create a simple login sequence in terminal but I can't figure out how to check if both the username and the password are in the same position in the list
usernames = ['username', 'hello']
passwords = ['password', 'world']
# my code so far:
from getpass import getpass
import time
import logins
username = input('Username: ')
password = input('Password: ')
print('Logging In...')
time.sleep(1)
def check_login(user, pasw):
if user in logins.users and pasw in logins.passes:
print('Valid')
else:
print('Invalid user and password, try again.')
check_login(username, password)
#It works except for the fact that i can input (username, world) or (hello, password)
#I'm trying to check that each username and password are in the same order (0,0, 1,1, etc) and
#return it as valid. Any help is appreciated :)
You can use zip:
def check_login(user, pasw):
if (user, pasw) in zip(logins.users, logins.passes):
print('Valid')
else:
print('Invalid user and password, try again.')
If you are to call this method repeatedly, it is better to create a O(1) lookup structure:
lookup = dict(zip(logins.users, logins.passes))
def check_login(user, pasw):
if lookup.get(user, None) == pasw:
print('Valid')
else:
print('Invalid user and password, try again.')
From what I get about this question, you can just check their indices using index inbuilt to lists to assert if both the user and password are at the same location.
def check_login(user, pasw):
if user in logins.users and pasw in logins.passes and logins.users.index(user)==logins.passes.index(pasw):
print('Valid')
else:
print('Invalid user and password, try again.')

Weird Functions Calling and Inconsistent Result

First, I just want to say I'm a newbie, and I apologize for the bad explanation and the long post...
So, as a practice, I wrote a simple python login system with a JSON file where the profiles are stored.
Everything was going well, but all of a sudden my code started behaving weirdly.
this is my main.py file:
import json
with open("profiles.json") as f:
profiles = json.load(f)
def main():
print("-----------------Main--------------------")
option = input("[L]ogin | [S]ign up: ").upper()
if option == "L":
login()
elif option == "S":
sign_up()
else:
print("Please select a valid option.")
main()
def login():
print("-----------------Login--------------------")
username = input("Username: ")
password = input("Password: ")
check_credentials(username, password)
def sign_up():
print("-----------------Sign up--------------------")
new_username = None
new_password = None
# check if this username already exists, return to sign up if true
def username_match():
nonlocal new_username
new_username = input("Username: ")
for profile in profiles["profiles"]:
if new_username == profile["username"]:
print("This username is taken.")
username_match()
# loop back if the passwords do not match
def password_match():
nonlocal new_password
new_password = input("Password: ")
confirm_password = input("Confirm Password: ")
if new_password != confirm_password:
print("Passwords do not match.")
password_match()
username_match()
password_match()
security_question = input("Security Question: ")
security_answer = input("Security Question Answer: ")
profiles["profiles"].append({"username": new_username,
"password": new_password,
"security_question": security_question,
"security_answer": security_answer})
with open("profiles.json", "w") as w:
json.dump(profiles, w, indent=2)
check_credentials(new_username, new_password)
def profile_settings():
input("-----------------Options--------------------"
"\n"
"[P] change password | [U] change username"
"\n"
"[S] change security question | [E] add email"
"\n"
"What would you like to do: ").upper()
print("\nThis section is under construction. Please visit later.")
def check_credentials(username, password):
print("\nchecking credentials...\n")
for profile in profiles["profiles"]:
if profile["username"] != username and profile["password"] != password:
print("Wrong username and password, please try again.")
login()
if profile["username"] == username:
print(f"found username: {username}")
if profile["password"] == password:
print(f"found password: {password}")
else:
print("Wrong password, please try again.")
login()
else:
print("Wrong username, please try again.")
login()
profile_settings()
main()
and this is my profiles.json file:
{
"profiles": [
{
"username": "Hakobu",
"password": "123",
"security_question": "favorite food",
"security_answer": "lemon"
},
{
"username": "Mohammed",
"password": "345",
"security_question": "1",
"security_answer": "1"
}
]
}
Here is what I found weird:
When I try to login to a second profile, it tells me, wrong credentials and put me back to the login() function, but it lets me in for the first profile.
when trying to make a new profile through the sign_up() function, it is supposed to automatically log in but beyond the first profile, the second profile created just does the same thing, it tells me, wrong credentials and put me back to the login() function.
when successfully logging in with the first profile, the profile_settings() function gets called. it's supposed to close after inputing anything, but instead it goes back to the check_credentials() function, says I input the wrong username and password, then going to the login() function straight after the profile_settings() function even though I have not called them anywhere in the profile_settings() function
I have no idea why in god's name this happens. It was working fine just a little bit ago. Tried commenting out the code I wrote after it was working but nothing worked. I have a huge headache now and my back hurts.
After learning about stack calls and stack frames, I now know that the issue was simply the for loop getting resumed after exiting the check_credentials() resulting in what seemed to be an infinite loop of that function.
Here is the improved code:
def check_credentials(username, password):
print("\nchecking credentials...\n")
username_found = False
password_found = False
for profile in profiles["profiles"]:
if profile["username"] == username:
print(f"found username: {username}")
username_found = True
if profile["password"] == password:
print(f"found password: {password}")
password_found = True
break
if not username_found and not password_found:
print("Wrong username and password, please try again.")
login()
elif not username_found:
print("Wrong username, please try again.")
login()
elif not password_found:
print("Wrong password, please try again.")
login()
profile_settings()

Can not get "while" statement to progress [duplicate]

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.

Password Checker loop not working

I have tried to create an app in Python that makes a user create a password and then makes them verify it. Obviously I had to create a loop so that when the user entered an unmatching password they had to try again. I am not very experienced with loops so here is what I got. How do I make this work?
here is the code:
password = raw_input ("Create a password: ")
passwordv = raw_input ("Retype your password: ")
a = ("Passwords don't match! Please try again!: ")
b = ("Congrats, you have created a password")
def password():
if password == passwordv :
print ("Congrats, you have created a password")
else :
print (a)
return password
return passwordv
while password !=passwordv:
print (a)
here is another set of code trying to do the same thing:
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
while (password != passwordv):
print raw_input('Passwords do not match, try again: ')
if (password == passwordv) :
print ('Password set')
break
Your conditional to test whether the passwords match was included in the loop which checks that they don't match -- so, it never gets run.
Try this instead:
password = raw_input('Create a password: ')
passwordv = raw_input('Verify your password: ')
while (password != passwordv):
print raw_input('Passwords do not match, try again. ')
password = raw_input('Create a password: ')
passwordv = raw_input('Verify your password: ')
continue
print ('Password set')
Note how only the code that should be run if the passwords don't match is included within the while loop.
What you need here is an "N and a half times loop". To avoid repeating code (guided by the DRY principle) you might consider writing a function to get the passwords. The following might work:
def get_passwords():
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
return password, passwordv
pw1, pw2 = get_passwords()
while pw1 != pw2:
print "Sorry, passwords do not match"
pw1, pw2 = get_passwords()
The loop won't be entered at all if the original passwords match. Otherwise it will repeat until they do.
password=raw_input('Enter password: \t\t\t')
passwordv=raw_input('Enter password again to verify: \t')
if password == passwordv:
print "\ncongratz you have created password"
else:
print "\nPlease try again...!"
while password != passwordv:
password=raw_input("Enter password: \t\t\t")
passwordv=raw_input("Enter password again to verify: \t")
if password == passwordv:
print"\ncongratz you have created password"
else:
print"\nPlease try again...!"
I know this one is long, It is just for basic understanding
The other answers provide the code that will do what you want. I thought that it could be interesting to tell you a little bit more what was wrong with the code you provided because the problem is more about your understanding of how things work.
1st attempt: a variable and a function have the same name
# Here you define your password variable as a string
password = raw_input ("Create a password: ")
[...]
# And then you reassign it here: it contains now the address of that function!
def password():
[...]
# Now you're comparing a function to a string: they'll never be equal
while password !=passwordv:
[...]
This could have been avoided simply by changing the name of your function (which is never called by the way so I'm not sure what you wanted to do but I thought you might find that interesting). Further reading: Python: function and variable with same name
2nd attempt: the values of the variables stay the same
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
# At this point, if the test is true, you'll reach the end of the code without
# displaying the 'Password set' message you wanted
while (password != passwordv):
# This only prints a message
print raw_input('Passwords do not match, try again: ')
# The condition below can never be true: you just tested that they were
# different but did nothing to give them new values!
if (password == passwordv) :
print ('Password set')
break
The way to fix that is what the other answers provide: take your message out of the loop (getting out of the loop means that your condition was met) ; make sure that you do something inside the loop that will assure that the next test will be different from the previous one (otherwise, you will end up testing the same values over and over again) ; to avoid breaking inside the loop, set your values outside the loop, and then get new values inside the loop in case the initial test failed.
Here's an idea:
First define these:
MinPass = 6
MaxPass = 12
Then this:
print ("Now, lets try with a password. Please enter one here")
EnteredPassword = input("Password: ")
while len(EnteredPassword) < MinPass:
print ("That password is too small. Please try again")
EnteredPassword = input("Password: ")
while len(EnteredPassword) > MaxPass:
print ("That password is too long, please try again")
EnteredPassword = input("Password: ")
Hope this helps!

Categories

Resources