Home>

### about for syntax i want to know the reason why the result is different depending on where the initial value is defined python

Define the initial value a before the for syntax and

``````a = 1
for i in range (1,5):
a = a + i
print (a)``````

Then the result is
2
Four
7
11
Is output,
In this way, if you set the initial value b in the for syntax,

``````for i in range (1,5):
b = 1
b = b + i
print (b)``````

2
3
Four
Five
Is output. Why do the results differ if the same initial value is given but in different locations?
The letters a and b have no particular meaning.

• Answer # 1

To someone

Remember 1
Add 1 to the number you remember. Please say that number
Add 2 to the number you remember. Please say that number
Add 3 to the number you remember. Please say that number
Add 4 to the number you remember. Please say that number

When

Remember 1
Add 1 to the number you remember. Please say that number
Forget the numbers you remember and remember 1
Add 2 to the number you remember. Please say that number
Forget the numbers you remember and remember 1
Add 3 to the number you remember. Please say that number
Forget the numbers you remember and remember 1
Add 4 to the number you remember. Please say that number

Imagine the result when you instruct.

• Answer # 2

In the case of the above example
After assigning a value to a, the loop repeats.
result
a (1) +1 = 2
a (2) +2 = 4
a (4) +3 = 7
a (7) +4 = 11
It will be.
In contrast, the example below assigns a value to b in a loop.
Therefore, the value of b is reset to 1 every time.
result
b (1) + 1 = 2
b (1) +2 = 3
b (1) +3 = 4
b (1) +4 = 5
It will be.