0

In my project I have user made variables. What I'm trying to do is print the variable if the user gives a string named the same as the variable. Here's what I think it would look like:

variable = 123
userInput = input("Enter a variable to print: ")
print(userInput)
# Instead of printing userInput, it will check if userInput is the name of a variable, 
# and print if it is.

The user will input "variable", and will print 123. Also note that the variables will have their custom names and data. So if the variable name is something different, user entering "variable" won't cause it to be printed.

And yes, I know that having user-made variables can be a bad idea. I know what I'm doing.

Expliked
  • 101
  • 10
  • Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – Robin Zigmond Jun 06 '20 at 10:15
  • It `variable` is local to the current function, you can use `locals()[userInput]`. If it's global, you can use `globals()[userInput]`. – Tom Karzes Jun 06 '20 at 10:16
  • Does this answer your question? [How to get the parameter name of an argument passing into a function in Python?](https://stackoverflow.com/questions/62181239/how-to-get-the-parameter-name-of-an-argument-passing-into-a-function-in-python) – Joe Jun 06 '20 at 11:36

3 Answers3

0

You can access your variables dynamically by their name using globals():

print(globals().get(userInput,"No such variable"))

You can replace "No such variable" with any other default value in case the variable doesn't exist

Gabio
  • 9,126
  • 3
  • 12
  • 32
0

You can create a userspace for each user with their own variables, i.e

def get_userspace(user):
    """ Returns current userspace of user. """
    # Here may be Postgres, Redis or just global userspaces
    global userspaces
    return userspaces.setdefault(user, {})

userspaces = {}
userspace = get_userspace(user)

then place all input of specific user in his/her userspace to not interfere with others and to not redefine locals/globals that can be viable for program execution. An then use your code with little improvements to get variable from that userspace:

user_input = input("Enter a variable to print: ")
print(userspace.get(user_input))
frost-nzcr4
  • 1,540
  • 11
  • 16
-1

Here you go.

variable = 123
userInput = input("Enter a variable to print: ")
print(globals()[userInput])