A community for students.

Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing

anonymous

  • 5 years ago

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

  • This Question is Closed
  1. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    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

  2. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

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

  3. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    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)

  4. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    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])

  5. carlsmith
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    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.

  6. Not the answer you are looking for?
    Search for more explanations.

    • Attachments:

Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy

Your question is ready. Sign up for free to start getting answers.

spraguer (Moderator)
5 → View Detailed Profile

is replying to Can someone tell me what button the professor is hitting...

23

  • Teamwork 19 Teammate
  • Problem Solving 19 Hero
  • You have blocked this person.
  • ✔ You're a fan Checking fan status...

Thanks for being so helpful in mathematics. If you are getting quality help, make sure you spread the word about OpenStudy.

This is the testimonial you wrote.
You haven't written a testimonial for Owlfred.