我一直试图将新创建的用户密码存储到我的登录系统项目的指定用户名中,但是,始终会出现类型错误,而且我不确定如何将密码值更改为整数或解决问题。谢谢你的帮助
user = []
status = ""
status = input("Have You Registered With Our System? y/n")
username = input("Choose A Username: ")
if username in user:
print("Username is already in use")
else:
createPassword = input("Create Your Password: ")
user[username] = createPassword
print("\n User Has Been Created \n")
login = input(" Enter login name: ")
password = input( " Enter Password: ")
if login in user and user[login] == password:
print("\n Successfully loged in\n")
#with open("user.txt", "w") as f:
f = open("user.txt", "a")
#print(f.mode)
#f.close()
f.write(login)
f.write(" ")
f.write(password)
f.write(" ")
f.close()
else:
print("\n User Does Not Exist or Wrong Features")
答案 0 :(得分:0)
您的user
是python 列表。
只需按照您的意图使用python 字典,代码就可以完美运行:
第一行:
user = {}
答案 1 :(得分:0)
您击中TypeError
的原因是因为lists
是用整数值而不是字符串索引的。
我认为dictionary在这里可能会更有帮助,因为您可以将strings
,ints
甚至tuples
存储为键(但不能存储{{1} },lists
或sets
):
dicts
这有一些优点。首先,对于大量数据,users = {}
username = 'testuser'
password = '1234knaoiva'
if username in users:
if password != users[username]:
raise ValueError("Invalid Password")
else:
print("Login successful")
else:
users[username] = password
print("Welcome, new user!")
中成员资格的测试要快得多,并且不会随着字典大小的增加而变化。测试dict
的成员资格会增加它包含的更多值(在您的情况下为用户)
显示这种情况如何工作
list
要显示在小型和大型数据组上进行成员资格测试(最坏情况)的性能差异:
users = {} # Users is an empty dictionary
username = input("What's your username? ") # testuser
username in users
# False
# Fails membership test
users[username] = input("What's your password? ") # testpass
users
# {'testuser': 'testpass'}
users[username]
# testpass
# List
python -m timeit -s 'd = [i for i in range(100)]' '999999 in d'
1000000 loops, best of 3: 0.801 usec per loop
# Dict
-m timeit -s 'd = {i: None for i in range(100)}' '999999 in d'
10000000 loops, best of 3: 0.0262 usec per loop
对于少量数据,您不会发现太大的差异(在现代处理器上),尽管即使只有100个元素,# List
-m timeit -s 'd = [i for i in range(1000000)]' '999999 in d'
10000000 loops, best of 3: 8.34 msec per loop
# Dict
-m timeit -s 'd = {i: None for i in range(1000000)}' '999999 in d'
10000000 loops, best of 3: 0.0343 usec per loop
的速度也要快一个数量级。用量较大时,差异是天文数字
答案 2 :(得分:0)
这是因为username
的类型是'str'而不是int,除非用户名全为0和1,否则您不能将其转换为int。
我建议使用字典来保存用户名和密码:
user = {}
# in creating password:
createPassword = input("Create Your Password: ")
user[username] = createPassword // This works because dictionary keys can be str
print("\n User Has Been Created \n")
然后检查用户名是否在您使用的if name in user.keys():
字典中