-1

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.

5
  • 1
    You can create a list, l = list(), then use l.append() to store values Commented May 12, 2016 at 22:51
  • Why do you want separate variables n1, n2, n3, etc, rather than using a list, such as n[1], n[2], n[3], etc.? (Or better, n[0], n[1], n[2], etc.) Python is designed to do this, not what you are asking. Commented May 12, 2016 at 22:52
  • 2
    Stop! If you don't know how to use a list or dict, spend some time to learn the basic of python before writing anything that doesn't make sense. In the code above, the line (n + x) = input(...) is definitely wrong. Commented May 12, 2016 at 22:56
  • Also len(p) is going to give you the length of the input string (for numbers 1-9, it will always return 1), you probably want int(p), being aware that it's going to error if someone provides a non-integer input string. Commented May 12, 2016 at 23:00
  • i am sorry for my ignorance as i am only a beginner, Thank you for the feed back. Commented May 12, 2016 at 23:05

2 Answers 2

2

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?

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

2 Comments

everything is relative. And besides, that is what i am trying to acheive, the bigger the number is and the more variables there will be
@GwendalDelisleArnold: It's still a bad solution.
0

I see what you're trying to do, but I am not aware of a way to create variables like you're attempting.

Instead, you could use a list, and append the user input to the list. Or you could try using a dictionary for similar results.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.