I'm just learning to program and am learning Python as my first language. As an exercise I'm trying to write an address book program. New contact are created by the user using the command prompt. New contacts are object instances of the Contacts class.
I know how to instantiate a class object from within the code, but how do I create one with a variable name based on user input? Say I prompt the user for a name -- how do I take that info and use it for the variable name of my new object?
Thanks!!
In programming, dynamic variable names don't have a specific name hard-coded in the script. They are named dynamically with string values from other sources.
A dynamic variable name, sometimes called a variable, is a variable with a name that is the estimation of another variable. Despite the fact that Python is a very dynamic language in which nearly everything is an object, it is possible to construct dynamic variables in Python.
Using exec() method to create dynamically named variables Here we are using the exec() method for creating dynamically named variable and later assigning it some value, then finally printing its value.
Use the input() function to get Python user input from keyboard. Press the enter key after entering the value. The program waits for user input indefinetly, there is no timeout. The input function returns a string, that you can store in a variable.
From the comments, it turns out you are asking about something that gets asked more than once on here. "How can I create dynamically named variables".
Answer: Don't do this. Chances are there are better ways to solve the problem.
Explanation:
If you were to create dynamically named variables, you don't quite have a good handle to them once they are created. Sure there are ways to check the globals and local scopes to see what is there. But the fact is that you should have definitive control over what is being created.
What you should do is put them into a dictionary:
people = {}
name = raw_input("What name? ") # "person"
people[name] = User(name)
print people
# {'person': <User: "person">}
print people.keys()
# ['person']
This way you are not creating arbitrary variables in your namespace. You now have a dictionary of keys and objects as values. It is also a can of worms to allow a user-supplied input to drive the naming of a variable.
For more info, just search on here for the same topic and see numerous examples of why you should not do this. No matter what examples you see showing you how to use globals(), etc, please take my advise and don't go that route. Love and enjoy..and maybe hug and kiss, your dictionary.
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With