简体   繁体   中英

How do I compare two variables which both contain strings in python?

I'm making a account login system in python by having the username and password stored in a separate file and the program access it, then read the password and compare it with what the user has entered. It can read the password in the file but for some reason when it compares it to what the user has entered, it always says it's wrong.

I've tried comparing the actual password to the user's input and I know it's reading the file right as I made it print out what it read and it printed the correct password. I've also made it print the user's input to make sure that's right and that was working too.

Just so you know, the file already exists which contains the password on the second line and it finds the right file as the file is named after the account that it's for.

Account = str(input("Enter the username. "))
Account_Password = str(input("Enter the password. "))
AccountFileName = (Account + ".txt")
with open(AccountFileName,"r") as AF:
    for x, line in enumerate(AF):
        if x == 1:
            Account_Password_Check = (line)
if Account_Password == Account_Password_Check:
    print("Welcome, " + Account + "!")
else:
    print("Either the username or password were incorrect.")

If the user input is the same as the password, it should print, "Welcome (username here)!" and if they're different then it should print, "Either the username or password were incorrect."

If you know what's wrong, please let me know.

Thanks.

In comments to your question, you will find the first reason why it doesn't work, but:

for x, line in enumerate(AF):
        if x == 1:
            Account_Password_Check = (line)

Is also not fully correct, enumerate start count from zero, but condition checks 1 line, it means that you will compare your current user password from previous. The correct version will be

for x, line in enumerate(AF):
        if x == 0:
            Account_Password_Check = line.strip()
            break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM