Search code examples
pythoninputvariable-selection

How to use user input to access a variable?


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?


Solution

  • 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}')