'why does this accept any username as long as password is correct
username = input("Welcome, please enter your username.")
password = input("Please enter your password.")
if username != "tony" and password != "password123":
print("Access Denied.")
else:
print("Welcome to the jungle")
Solution 1:[1]
Will try to make you understand by AND gate.
| A | B | C | D | E |
|---|---|---|---|---|
| username | password | username!=Tony | password!=password123 | Colmn_C AND Colmn_D(Access denied) |
| Tony | password123 | FALSE | FALSE | FALSE |
| Hulk | Password123 | TRUE | FALSE | FALSE |
| Tony | xyz | FALSE | TRUE | FALSE |
| Hulk | xyz | TRUE | TRUE | TRUE |
So you can see ,why Access is denied only when both are incorrect
Solution 2:[2]
Change the test to:
if username != "tony" or password != "password123":
or turn the whole thing around:
if username == "tony" and password == "password123":
print("Welcome to the jungle")
else:
print("Access Denied.")
That (IMO) makes it more clear both the username and the password need to be correct.
Solution 3:[3]
Good news, your code is written correctly!.
Bad news, your code is not doing what you want.
Try to read your conditional out load.
Your computer: 'if the user name is not "tony" and the password is not "password123," I should deny access.
Everything else I should accept.'
That means, when only one of them is wrong, it is ok!
Solution 4:[4]
just change the statements or change the condition AND with OR
solution1
username = input("Welcome, please enter your username.")
password = input("Please enter your password.")
if username != "tony" or password != "password123":
print("Access Denied.")
else:
print("Welcome to the jungle")
solution2
username = input("Welcome, please enter your username.")
password = input("Please enter your password.")
if username != "tony" and password != "password123":
print("Welcome to the jungle")
else:
print("Access Denied.")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tomato Master |
| Solution 2 | Anthon |
| Solution 3 | Blind2k |
| Solution 4 | Amit |
