Is there a way to create a variable after user input? Multiple ones, rather. For example, I'm writing a simple little program that records what page you're on in a book, but I'd like it to record as many books as the user needs. So, for example, the program would ask a user how many books they would like to record bookmarks for. If the user inputs 5, it would create 5 randomly named variables, and be able to read them back at a later time. I should be fine writing everything on my own, but I would need to know, is there a way to create a variable from user input, and if so, how?
-
1How about using a list instead?squiguy– squiguy2012-12-12 22:07:51 +00:00Commented Dec 12, 2012 at 22:07
-
Don't create 5 randomly named variables! Put them in a list of length 5!David Robinson– David Robinson2012-12-12 22:08:03 +00:00Commented Dec 12, 2012 at 22:08
-
1Or a dictionary? Use the randomly generated names as keys and a list of bookmarks for the values.Garrett Hyde– Garrett Hyde2012-12-12 22:08:11 +00:00Commented Dec 12, 2012 at 22:08
-
@squiguy Wow, that just flew right over my head. Simple and clean. Thank you! If you'd like your answer accepted, you could leave it as an actual answer and I'll accept it.MalyG– MalyG2012-12-12 22:11:02 +00:00Commented Dec 12, 2012 at 22:11
-
@GarrettHyde Another good idea. Whoever writes theirs as an actual answer first can have the accepted answer (you, or @squiguy)MalyG– MalyG2012-12-12 22:11:42 +00:00Commented Dec 12, 2012 at 22:11
Add a comment
|
3 Answers
While you have the right idea, it's the wrong implementation. Try a list instead:
newlist = []
for i in range(pages):
newlist.append(<variable>)
And then access them with:
newlist[slot]
EDIT:
As suggested by a commenter, you could use a dict too. They are useful.
mydict = {}
books = input().split(", ")
for book in books:
mydict[book] = <variable>
This short program will let you input books in the form of
cool book, to kill a mockingbird, book of evil
Then use it like:
mydict['to kill a mockingbird']
to access your variable.
2 Comments
Silas Ray
If newlist is a dict with the keys being the title or some other identifier for a book, there's no need for any limit (other than memory/performance constraints) on the number of books, and you don't need to separately record the mapping from id to book.
SuperDisk
@sr2222 Added your recommendation