Search code examples
pythonvariablesuser-defined

defining variable names with integer values defined by user in python


I am currently trying to write a simple program to calculate probabilities of possible combinations with dice of different sizes (e.g. : 6, 12, 4, 20). The problem i have is that it is supposed to be user friendly and work with ever int value the user puts. The problem i am having here is the following :

p = input('How many dice do you have ? :')

a = len(p)

x = 0
while x != a :
    x += 1
    (n + x) = input('What is the amount of faces of your ' + x + 'die ? :')
    # here i want to create a variable named n1, n2, n3,... until the loop stops.

Can someone help me find a way around this without having to import dictionaries.


Solution

  • You can create variables procedurally by modifying the locals() dictionary.

    for i in range(3):
        var_name = 'var{}'.format(i)
        locals()[var_name] = i
    
    print var0, var1, var2
    # 0 1 2
    

    That being said, you probably shouldn't do this. A list or dictionary would be better and less error prone. For someone looking at your code, it won't be clear where variables are being defined. Also, it doesn't make coding your application any easier, because you won't know ahead of time what variables are going to exist or not, so how are you going to use them in your code?