我想阅读并确认字典中的数据

时间:2017-06-07 10:47:09

标签: python-2.7

我想为现有用户编写一个简单的登录脚本,我已经为它创建了一个字典,但我的代码不起作用。

我尝试过以下方法:

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!"

代码不起作用,我的密码总是不正确。

3 个答案:

答案 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_namepassword,这使得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!"