使用多个变量在python中创建一个列表作为if语句的一部分

时间:2014-04-10 00:53:57

标签: python list function python-2.7 if-statement

   def runUser():
       x = raw_input("Enter your username:")
       y = raw_input("Enter your password :")
       users = [x == "aeduun" and y == "1234", x == "paul" and y == "fifty"]
       raw_input("")
       if x == users[] and y == users[]:#x == "aeduun" and y == "1234":
           print "you are now logged in"
       elif x == "Mercuryisle" and y == "shrek":
           print "Your account has expired..." \
                 "You will now bw taken back to the login page"
           time.sleep(5)
       return runUser()

这是我编译为python 2.7的小测试项目的一部分的代码。在这里我试图伪造一个基本登录与变量列表的密码和用户名。该函数能够读取变量之间的关系,但包含对不同列表项的引用的错误。 当我启动程序时,所有发生的事情都是调用无效的用户名(代码不显示)。 我想要一些关于如何初始化列表项索引的建议,以及它们将作为if语句的一部分读取的方式。

2 个答案:

答案 0 :(得分:3)

以明文存储密码是不安全的,但鉴于此,我认为您可能会受益于元组和集合的使用,即

users = set([("aeduun","1234"), ("paul","fifty")])
expired_users = set([("Mercuryisle", "shrek")])
. . .
if (x,y) in users:
    print "you are now logged in
elif (x,y) in expired_users:
    print "Your account has expired..."
. . .

答案 1 :(得分:1)

def runUser():
   x = raw_input("Enter your username: ")
   y = raw_input("Enter your password: ")
   users = {"aeduun":"1234", "paul":"fifty"}
   raw_input("")
   if x in users:
       if y == users[x]:
           print "you are now logged in"
   elif x == "Mercuryisle" and y == "shrek":
       print "Your account has expired..." \
             "You will now bw taken back to the login page"
       time.sleep(5)
   return runUser()

运行方式:

>>> runUser()
Enter your username: aeduun
Enter your password: 1234

you are now logged in
Enter your username: Mercuryisle
Enter your password: shrek

Your account has expired...You will now bw taken back to the login page
Enter your username: 

只是一个建议,使用getpass.getpass()来获取密码,它可以防止字符回显。