Simple Login Function In Python
Solution 1:
You call your login()
function two times. Only the second one utilizes the return value, so you can remove the first call
def main():
login() # <--- Remove this one
log = login()
Something you may wish to consider using is getpass
. Using this instead of raw_input
on your password field will prevent the password from being displayed on screen.
import getpass
...
def login():
...
passw = getpass.getpass("Password: ")
The rest of the code then behaves the same, but on the console, the output looks like this:
Username: max2Password:
Login successful!
Notice that the "Password:" line is empty, despite typing in a valid password
Solution 2:
The problem here is that you are calling login()
twice whitin main
. To fix your bug, just remove the first call since the return is not even used. Also, I'm not sure whether it's intended but:
if (user in us) and (passw in pw):
will match ('user', 'pass') even if (us, pw) is ('username', 'password'). Use ==
operator instead.
One least thing, you should consider changing:
us, pw = line.strip().split("|")
To:
us, pw = line.strip().split("|", 1)
Which splits the line only once, otherwise the passwords won't be able to contain |
Solution 3:
The issue was that there were two instances of login() being called. The following Code Will Repeat The Login until it is correct:
deflogin():
user = raw_input("Username: ")
passw = raw_input("Password: ")
f = open("users.txt", "r")
for line in f.readlines():
us, pw = line.strip().split("|")
if (user in us) and (passw in pw):
print"Login successful!"returnTrueprint"Wrong username/password"returnFalsedefmenu():
#here's a menu that the user can access if he logged in.defmain():
globalTruewhileTrue:
True = True
log = login()
if log == True:
menu()
True = False
main()
Post a Comment for "Simple Login Function In Python"