views:

281

answers:

4

In Python, if I were to have a user input the number X, and then the program enters a for loop in which the user inputs X values, is there a way/is it a bad idea to have variable names automatically increment?

ie:
user inputs '6'
value_1 = ...
value_2 = ...
value_3 = ...
value_4 = ...
value_5 = ...
value_6 = ...

Can I make variable names increment like that so that I can have the number of variables that the user inputs? Or should I be using a completely different method such as appending all the new values onto a list?

+9  A: 

You should append all the values to a list, that allows you to easily iterate through the values later as well as not littering your namespace with useless variables and magic.

knutin
+6  A: 

should I be using a completely different method such as appending all the new values onto a list?

Yes, you can use a list. You can also use a mapping for this.

make variable names increment like that

No. That's a horrifyingly bad idea.


"but just out of complete curiosity, is these a way to do it in the asked manner?"

Yes, but it's clearly a horrifyingly bad idea. So, there's no point in showing it. It's a terrible, terrible thing to even attempt.

S.Lott
+1  A: 

While using a list or dictionary is of course the right approach here, it is possible to create named variables, using exec(). You'll miss out on all the convenient operations that lists and dictionaries provide (think of len(), inserting, removing, sorting, and so on), but it's possible:

count = raw_input('Number of variables:')
for i in xrange(count):
    exec('var_' + str(i) + ' = ' + str(i))

exec() accepts and executes strings that contain valid Python expressions. So the above piece of code is generating and executing code on the fly.

Pieter Witvoet
A: 

What if I have 10 text fields in HTML and I want to check them all to make sure they are valid strings(in the same way of course). Now I have to have unique if statements for each field since the names are different. It would be nice to have a for loop to increment a unique number next to the field name, making a lot less code to write

Will