Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment variable names/Is this a bad idea [duplicate]

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?

like image 944
tom Avatar asked Mar 21 '10 19:03

tom


People also ask

Is it okay to have long variable names?

Most functions only contain two or three variables, so a long name is unnecessary.

Why is it a bad idea to reuse the same identifier in different nested scopes?

You may get compiler warnings if you create a variable with the same name as another variable in an outer scope. With good reason, because that is going to be confusing and error prone. Avoid it whether you get warnings or not.

Can you increment a variable name in python?

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

Why use short variable names?

Comments also allow you to create a context for your code, so that short variable names make sense. If you have made clear that the context is computational geometry, then p, q, x, y, z, u and v variables make a lot more sense.


1 Answers

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.

like image 57
Pieter Witvoet Avatar answered Oct 11 '22 02:10

Pieter Witvoet