Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 8 Online
OpenStudy (anonymous):

I'm new to Python. How how can I append a counter to a variable? ctr = 3 variable = variable3

OpenStudy (anonymous):

What are you trying to do? I don't quite understand the question. If you are trying to add 3 to any variable you can just use variable +=3 So, >>> ctr = 0 >>> ctr += 3 >>> ctr += 3 >>> print ctr 6

OpenStudy (anonymous):

variable = [] variable.append(ctr) ??????

OpenStudy (anonymous):

when you tried it did you get something like this in the traceback?: TypeError: cannot concatenate 'str' and 'int' objects maybe this: v = "variable" + str(ctr)

OpenStudy (anonymous):

If I'm understanding the question correctly, you are trying to programmatically create a variable name using information stored in another variable. While it is possible (with some magic) it's not recommended. Instead I would suggest storing the information into a dictionary or, if you are accessing sequential data, a list. e.g. variable = [] variable.append('ham') variable.append('eggs') variable.append('toast') print "For breakfast I'd like %s, %s and no %s" % (variable[1], variable[2], variable[0])

OpenStudy (carlsmith):

You can't. You just increment the value assigned to a variable ctr = ctr + 1 or ctr += 1 for short. You can assign the value of a variable to another. a = 5 ctr += a That's about it. The append method is for lists, for adding an object on to the end of an existing sequence of objects.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!