将raw_input answer设置为预定义变量

时间:2013-12-18 18:51:36

标签: python raw-input

新手在这里。

我想让Python查看变量(在这种情况下,john,clark和bruce)并吐出那些数组中的字符串,但我没有运气弄清楚如何。这是我正在研究的例子:

names = ("john", "clark", "bruce")

john = ("doe", "13-apr-1985")
clark = ("kent", "11-jan—1987")
bruce = ("wayne", "05-sep-1988")

user = raw_input("What is your name?")
if user in names:
  print "Your last name is: " + ????[0]
  print "Your date of birth is: " + ????[1]
else:
  print "I don’t know you."

问号是我被困的地方。我不知道如何将两者联系在一起。我希望我的问题不会太混乱。

3 个答案:

答案 0 :(得分:4)

您可以使用字典:

names = {
    "john": {
        "last_name": "doe",
        "date_of_birth": "13-apr-1985"
    },
}

user = raw_input("What is your name?")
if user in names:
    print "Your last name is: " + names[user]["last_name"]
    print "Your date of birth is: " + names[user]["date_of_birth"]
else:
    print "I don’t know you."

请注意,当多个人具有相同的名字时,此方法不起作用。在这种情况下,您需要调整数据结构以相应地处理(当您有人填写"john"时,您需要确定将显示哪些结果。)

答案 1 :(得分:4)

使用dictionary将名字映射到您拥有的元组。

names = { "john": (“doe”, “13-apr-1985”),
          "clark": (“kent”, “11-jan—1987”),
          "bruce": (“wayne”, “05-sep-1988”)}

user = raw_input(“What is your name?”)
if user in names.keys():
  print “Your last name is: “ + names[user][0]
  print “Your date of birth is: “ + names[user][1]
else:
  print “I don’t know you.”

为了使这更加pythonic和更容易使用,创建一个嵌套字典:

names = { "john": {"last": “doe”, "birthdate": “13-apr-1985”},
          "clark": {"last": “kent”, "birthdate": “11-jan—1987”},
          "bruce": {"last": “wayne”, "birthdate": “05-sep-1988”}}

user = raw_input(“What is your name?”)
if user in names.keys():
  print “Your last name is: “ + names[user]["last"]
  print “Your date of birth is: “ + names[user]["birthdate"]
else:
  print “I don’t know you.”

作为旁注,您可能希望在输入时修剪输入中的任何前导空格。

...
user = raw_input(“What is your name?”)
user = user.strip()
if user in names.keys():
  ...

答案 2 :(得分:2)

你应该在这里使用dict,就像这样

d = {"john" : ("doe", "13-apr-1985"),
     "clark" : ("kent", "11-jan-1987"),
     "bruce" : ("wayne", "05-sep-1988")}

...
...
if user in d:
    print “Your last name is: “ + d[user][0]
    print “Your date of birth is: “ + d[user][0]
else:
    print “I don’t know you.”