我在python中做了一个代码,让密码并保存在文本文件中,如果用户在文件中输入了相同的密码,就会出现错误代码。问题是,虽然我做了两条语句来检查密码是否有效,并且在文本文件中没有相同的密码,但检查文本文件的语句却发现相同的文件。你能告诉我,我哪里出错了吗?
def InputString():
String = str(input("Enter your password. :"))
return String
def CheckPassword(Password):
##I declared "Index","Upper","Lower","Digit" and "Other" as Integer.
##In python, there is no data type for
##"char", so We use string instead.
##I use "variable" as boolean for checking password.
Upper = 0
Lower = 0
Digit = 0
Other = 0
variable = False
for index in range(len(Password)):
NextChar = (Password[index:index+1])
if NextChar >= "A" and NextChar <= "Z":
Upper = Upper + 1
elif NextChar >= "a" and NextChar <= "z":
Lower = Lower + 1
elif NextChar >= "0" and NextChar <= "9":
Digit = Digit + 1
else :
Other = Other + 1
if Upper > 1 and Lower >= 5 and (Digit - Other) > 0:
variable = True
else :
variable = False
return variable
def CheckThrough (Password):
FileP = open("Password.txt","r")
if FileP.mode == 'r':
contents = FileP.read()
if contents == Password:
usable = False
else :
usable = True
FileP.close()
return usable
###The main programs starts here###
print("Enter the password.")
print("You must add at least 1 upper character.")
print("5 lower character")
print("and the difference between numeric character and symbols must be more than 1.")
variable = False
usable = False
while variable == False and usable == False:
Password = InputString()
variable = CheckPassword(Password)
if variable == True:
usable = CheckThrough(Password)
if usable == True:
print("You can use the password.")
elif usable ==False :
print("The password you entered is already used.")
else :
print("The error is ocuured.")
else :
print("You can't use this password, try again.")
print("Your password is",Password)
FileP = open("Password.txt","a+")
FileP.write(Password)
FileP.write("\n")
FileP.close()
你需要添加 .strip()
所以它没有空格,例如 String = str(input("Enter your password. :").strip())
. 当你输入密码时,有一个空格,但它不会被保存到文件中,因此它总是把它作为一个新的密码来读取。
我的输入 = 输入你的密码。 :Kingdom1hearTs.
程序的输入="Kingdom1hearTs"
(用打印的方式查看输入系统的内容)
和 if contents == Password:
需要 if Password in contents:
否则你看到的密码是否与整个txt文件相同。
NextChar = (Password[index:index+1])
if NextChar >= "A" and NextChar <= "Z":
Upper = Upper + 1
elif NextChar >= "a" and NextChar <= "z": #had the wrong indentation
Lower = Lower + 1
elif NextChar >= "0" and NextChar <= "9":
Digit = Digit + 1
else :
Other = Other + 1