Python Forum
Help please: WHILE LOOPS with BOOLEAN LOGIC
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help please: WHILE LOOPS with BOOLEAN LOGIC
#1
Dear all
Why does this code not work when the correct combination of username and password are entered?

username = input("Enter your Username: ")
password = input("Enter your Password: ")

while (username != "Jack" and password != "123") or (username != "Jill" and password != "345"):
          username = input("Enter your Username: ")
          password = input("Enter your Password: ")

print (".....Entering the System")
Yoriz write Jun-20-2021, 10:23 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
If one of your combinations of username and password is True the other combination will be False.
When using or x or y, if x is false, then y, else x
So your statement is the equivalent of
print(True or False)
print(False or True)
Which will always be True
Output:
True True
Reply
#3
Python's dictionary structure fits well with the task of usernames and passwords. Dictionaries work with key:value pairs
Restructuring, and not limiting you to 2 names:
pasta = False #would have used pass but that is a reserved word
codes = {'Jack':'123', 'Jill':'345'} #Dictionary of the users and pwds 

while not pasta:
    username = input("Enter your Username: ")
    password = input("Enter your Password: ")
    if username in codes.keys(): #Make sure username in the list
        if codes[username] == password: 
            pasta = True
print (".....Entering the System")
Output:
Enter your Username: Fred Enter your Password: Flintstone Enter your Username: Jack Enter your Password: 123 .....Entering the System
Reply
#4
You need to use and, not or
while (u != u1 and p != p1) and (u != u2 and p != p2):
Which translates to
Quote:while login does not match any account
By using or the logic is
Quote:while logic does not match all accounts
Avoid duplicate code. Initialize username and password to None and let the first password check fail. The code works the same but is shorter.

If using a dictionary of passwords, use get.
while codes.get(input('Username: ')) != input('Password: '):
Reply
#5
Thank you...this is fabulous.
I didn't really want to use Dictionaries, but I can see why you have and see the benefits.

Brilliant :-)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  conditionals with boolean logic?? ridgerunnersjw 3 1,995 Sep-26-2020, 02:13 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020