Ask coding questions

← Back to all posts
Can you make python make variable
RainBowLion1 (6)

Hello i want to make a code that makes a certain about of variable depending on the number i give it also with a prefix like "number_1" or "line_3". is this posible?

Answered by InvisibleOne (2935) [earned 5 cycles]
View Answer
InvisibleOne (2935)

You could just put all the values in a list and access them by indexing, but no, there isn't really a way to do what you want to, at least not a 'good' way.
However, as a master of Jank I know some little tricks to get the job done.
First, you need to put all the 'variables' you are creating into a multiline string, I'm assuming that their values will be the same for all of them initially.

i = int(input("How many vars do you want: ")
name = input("Name: ")
val = input("Value: ")

vars = """"""

for n in range(i):
  vars += name + '_' + str(n+1) + ' = ' + val + '\n'

Next you'll need some file writing skills.

with open('', 'a+') as file:

It if I did everything correctly it should have appended those variables to the bottom of your script.

RainBowLion1 (6)

@InvisibleOne that works perfectly but... is there a way i can also make it ask "how long do you want it to be?" for a list

btfuss (177)

Better idea:
Use the exec function!

Here is a template function:

function createVar(name, amount, value):
  for index in range(1, amount+1): #this makes it so it starts at 1
    exec(f'{name}_{index} = "{value}"' #or check if the value isnt a string
  1. Amount = Amount of variables with extra names
  2. Name = The name of the original variable!
  3. Value = The value of the variable