Search code examples
pythonraw-input

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.


Solution

  • 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():
      ...