简体   繁体   中英

Set raw_input answer as pre-defined variable

Newbie here.

I wanted to have Python to look through the variables (in this case, john, clark, and bruce) and spit out the strings in those arrays, but I'm having no luck figuring out how. Here's the example I was working on:

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

The question marks is where I am stuck. I don't know how to link the two together. I hope my question isn't too confusing.

You can use a dictionary:

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

Note that this approach wouldn't work when multiple people have the same first name. In that case you need to adapt the data structure to handle that accordingly (and you need to decide whose results you're going to display when someone fills in "john" ).

Use a dictionary to map the first names to the tuples you have.

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.”

To make this even more pythonic and easier to work with, make a nested dictionary:

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.”

As a side note, you probably want to trim any leading whitespace off the input while you're at it.

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

You should use a dict here, like this

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.”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM