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

Variables in for loops

Hello I am new to coding and have chosen to start off with the language python 3.x. I am running into a problem as when I declare a variable and insert it in a for loop the variable is not changed.

This can be seen as after running the code below the output remains as the original value of 5.

    i = 5

    for x in range(2):
     i + 1

    print(i)

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 :

You use i = ... to give it a value, then you do not use i = ... anywhere to give it a new value, so the value never changes. You need:

i = 5

for x in range(2):
 i = i + 1

print(i)

i + 1 alone is not an error, but it does the calculation and throws the result away, as you did not say what else to do with it.

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