为什么两个相等的变量不被视为相等?

时间:2019-03-18 15:42:07

标签: python if-statement

在python中进行编程时,我遇到了这个错误,当通过if X == Y时,两个肯定相等的变量并不相等:

相关代码段:

 usernameinput = input("Enter your username: ")
    print("Just a sec...")
    passwordinput = hashingAlgorithm2()
    for line in Database:
        IDNumber, Username, Password = line.split(",")
        if Username == usernameinput:
            print(passwordinput)
            print(Password)
            if passwordinput == Password:            (this is the line in question)
                print("Test")
                LoggedIn = True
                ID = IDNumber
    if LoggedIn == False:
        triesLeft = triesLeft - 1
        print("Your username or password is wrong, you have", triesLeft ,"tries left.")
        if triesLeft <= 0:
            The_Correct_Password

相关结果:

Enter your username: daniel
Just a sec...
Enter your password: **********
12894487843593301576106844
12894487843593301576106844

Your username or password is wrong, you have 2 tries left.

有人知道为什么会这样吗?

我什至不知道问题出在哪里,因为在if X == Y时两个变量都相等。

1 个答案:

答案 0 :(得分:1)

您可以通过将密码强制转换为int(假设您的哈希函数始终返回int)来解决该问题。

   usernameinput = input("Enter your username: ")
   print("Just a sec...")
   passwordinput = hashingAlgorithm2()
   for line in Database:
       IDNumber, Username, Password = line.split(",")
       if Username == usernameinput:
           print(passwordinput)
           print(Password)
           if passwordinput == int(Password):  # Change here          
               print("Test")
               LoggedIn = True
               ID = IDNumber
   if LoggedIn is False:
       triesLeft = triesLeft - 1
       print("Your username or password is wrong, you have", triesLeft ,"tries left.")
       if triesLeft <= 0:
           The_Correct_Password