Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I add to a variable everytime a loop happens in Python?

i’m trying to make a loop, and every time it loops it adds one to a variable. instead, it adds one as soon as the loop starts and never again.

i tried this:

for x in sweden:
  cnote = 0
  print(sweden.notes[cnote])
  cnote += 1
  print(cnote)

it’s meant to add one to cnote everytime it loops. issue is, it starts on one somehow and never adds again. anyone have an idea on how to fix this? i’m stumped, i’ve tried using cnote = cnote + 1, +=, and i can’t think of anything else.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue you’re facing is that ‘cnote’ is defined within the loop not outside it. Therefore, whenever it loops it will reset back to 0 and then add a 1. You should make the code as such:

cnote = 0
for x in sweden:
    print(sweden.notes[cnote])
    cnote += 1
    print(cnote)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading