0

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?

5
  • 1
    How about using a list instead? Commented Dec 12, 2012 at 22:07
  • Don't create 5 randomly named variables! Put them in a list of length 5! Commented Dec 12, 2012 at 22:08
  • 1
    Or a dictionary? Use the randomly generated names as keys and a list of bookmarks for the values. Commented 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. Commented 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) Commented Dec 12, 2012 at 22:11

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@sr2222 Added your recommendation
0

s = raw_input('--> ') --> 10

Then a simple for loop s number of times will loop 10 times. Create an array or dictionary to hold the inputs in it.

Comments

0

Yes, there are ways to do it, see below. Many will argue that you shouldn't do it though, usually for valid reasons.

globals()['variable'] = 42
print variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.