Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 647
Re-l Avatar asked Mar 18 '26 17:03

Re-l


1 Answers

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():
  ...
like image 57
Kyle Kelley Avatar answered Mar 20 '26 09:03

Kyle Kelley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!