1

Can you create new variables while a python script is on?

For example if you had infinite selection, you could make a new variable for each selection? Like if you choose answer1 it'll create a new variable choise1 = answer1, then if you choose answer3 after it'll create a new variable choise2 = answer3, and this goes on for as long as you want without having to make the variables in the code by hand.

Thanks in advance and sorry if the question is a bit confusing, don't really know how to word it 100%

HXLA
  • 21
  • 2
  • 2
    Use a dictionary for this – AzyCrw4282 May 04 '20 at 00:30
  • Take a look at [this answer](https://stackoverflow.com/a/1373185/7389264) to "[How to I create a variable number of variables?](https://stackoverflow.com/q/1373164/7389264)". If you really do _need_ to dynamically create variables, some of the other answers discuss that. – jirassimok May 04 '20 at 00:32
  • How would I go at implimenting this tho? If I have a variable called variable1 and I want to create a new variable thats called variable2, how do I do this in the code? – HXLA May 04 '20 at 00:35
  • 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) – AMC May 04 '20 at 01:21

1 Answers1

0

Use a loop and dictionary to create infinite variables. Here is some quick code I wrote. I hope it puts you in the right track!

variables = {}

while True:
    choice = input('Enter a choice: ')
    answer = int(input('Enter an number: '))

    variables[choice] = answer

    next_ = input('Continue? (y/n) ')
    if next_.lower() == 'n':
        break


print(variables)
dram95
  • 444
  • 1
  • 7
  • 15