1

I am creating a program in which I would like to prompt users for NYC boroughs, and use a general GPS coordinate of said borough. Part of my code for this is

df.loc[0,'BOROUGH'] = input('Borough:\n')
manhattan = [40.7831, -73.9712]
brooklyn = [40.6782, -73.9442]
staten_island = [40.5795, -74.1502]
queens = [40.7282, -73.7949]
bronx = [40.8448 ,-73.8648]

I would like to now use the input response to access the appropriate coordinates. For example, if the user inputs "Manhattan," I can use some variant of input().lower() to grab the corresponding borough data.

I know from this answer that, if I want to create a variable using input, I can do that. Is there a way to access a variable?

martineau
  • 119,623
  • 25
  • 170
  • 301
Yehuda
  • 1,787
  • 2
  • 15
  • 49
  • 3
    Why not use one dictionary with keys like "manhattan" rather than different variables? In any event, `globals()` is a dictionary, so you can use it to access variables as well as define this. But -- that is almost always a sign of poor design. – John Coleman Dec 06 '20 at 19:57
  • 1
    @JohnColeman Your comment reminds me of the classic quote from Gandalf in Lord of the Rings: "Throw yourself in next time, and rid us of your stupidity." How I didn't think of this is beyond me. Thanks. – Yehuda Dec 06 '20 at 19:59
  • You don’t call variables. You must be thinking of something else. – quamrana Dec 06 '20 at 19:59
  • @quamrana Please forgive the terminology error. I'm relatively new to this whole programming thing. – Yehuda Dec 06 '20 at 20:03
  • ok, but where *did* you get that terminology? – quamrana Dec 06 '20 at 20:06
  • @quamrana Invented it on the fly as I was writing the question, because I've heard the term "call" related to programming stuff. Let's blame heuristics and laziness. – Yehuda Dec 06 '20 at 20:07
  • Oh, I see. I hadn’t fully realised that people really did that. – quamrana Dec 06 '20 at 20:11
  • @quamrana I accept the dubious honor of introducing you to the beginner's side of SO ;) – Yehuda Dec 06 '20 at 20:13
  • 1
    lol :-). Anyway dictionaries are the way to go. – quamrana Dec 06 '20 at 20:14
  • 1
    Short answer: `gps_coords = globals()[input('Borough:\n')]` (has no error handling). – martineau Dec 06 '20 at 21:42

1 Answers1

0

This is one way of picking some data from a collection given a user input:

boroughs = {'manhattan':[40.7831, -73.9712],
'brooklyn': [40.6782, -73.9442],
'staten_island': [40.5795, -74.1502],
'queens': [40.7282, -73.7949],
'bronx': [40.8448 ,-73.8648]
}

while True:
    borough = input('Please enter a borough name: ').lower()
    if borough in boroughs:
        print(f'GPS coordinates of {borough} are {boroughs[borough]}')
    else:
        print(f'Unknown borough: {borough}')
quamrana
  • 37,849
  • 12
  • 53
  • 71