Search code examples
pythonstringvariablesprintingglobal-variables

How to print a variable that has the same name as an inputted string?


[Python] I have a function that's supposed to print the values of global variables. It takes in 1 argument (the global variable name), but as a string. How do I print out the global variable value that has the variable name of the string?

dogs = 3
cats = 4
def get_value(variable_name: str):
    print(variable_name)

I expect the output of get_value(dogs) to be 3, but the actual output is dogs.

I can't change the type value of the parameters. It has to be str.


Solution

  • You can use Python's built-in globals() function:

    dogs = 3
    cats = 4
    
    def get_value(variable_name: str):
        print(globals()[variable_name])
    
    get_value('dogs')
    get_value('cats')
    

    Output:

    3
    4