我想为现有用户编写一个简单的登录脚本,我已经为它创建了一个字典,但我的代码不起作用。
我尝试过以下方法:
d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
print "Please enter your username: "
user_name = raw_input()
print "Please enter your password: "
password = raw_input
for user_name,password in d:
if user_name in d and password in d:
print "great"
else:
print "Password incorrect!"
代码不起作用,我的密码总是不正确。
答案 0 :(得分:1)
d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
user_name = raw_input() #apple
password = raw_input() # red
if user_name in d.keys():
#check if username: apple == password : red (key=value)
if password == d.get(user_name)
print "great"
else:
print "Password incorrect!"
答案 1 :(得分:0)
有些事情你做错了:
raw_input()
raw_string()
可以将字符串作为参数,这样您就可以摆脱print
语句d
中,但您实际上应该在密钥中查找用户名并在密码中查找值。已经在for循环上方定义了更多user_name
和password
,这使得for循环完全错误。因此,一个简单的解决方案是:
d = {'apple': 'red', 'green': 'lettuce', 'yellow': 'lemon', 'orange': 'orange'}
user_name = raw_input("Please enter your username: ")
password = raw_input("Please enter your password: ")
if password == d.get(user_name):
print True
else:
print False
答案 2 :(得分:0)
您将收到错误:“对于user_name,密码在d:”
Python ValueError: too many values to unpack
正确的代码将是:
d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
print "Please enter your username: "
user_name = raw_input()
print "Please enter your password: "
password = raw_input()
for user,passw in d.iteritems():
if user == user_name and password == passw :
print "great"
exit(0)
print "Password incorrect!"