Reputation: 63
I am new to coding and just stumbled upon these lines of code in "python"
a = [1,2,3,4,"hello"]
for i in a:
try:
print(i)
i + 1
print (("i is : %d") %(i))
except:
print("nope " + i + " is a string")
The output is:
1
i is : 1
2
i is : 2
3
i is : 3
4
i is : 4
hello
nope hello is a string
1) My question is why doesnt i get incremented? 2) why doesnt i=2 i in the second print statement? 3) Does "i" get incremented at all?
Upvotes: 0
Views: 36
Reputation: 6528
Because you are not over writing the variable. What you want is:
i += 1
What your code do is actually computing i+1
but it does not update the variable.
But the idea of a for loop is not to have to increment the variable yourself. It is incremented the next iteration. It you want a more complicated iteration pattern it is preferable that you create it before.
Upvotes: 1