Home > Blockchain >  Why i = 1, and i = i 1 would become 2?
Why i = 1, and i = i 1 would become 2?

Time:07-13

i = 1
i = i   1
print(i)

Hi, I am a python beginner, and I'm pretty confused about the code's logic. Why i would eventually become 2?

Thank you

CodePudding user response:

'i' is a variable which stored 1 if We add 1 again in 'i' thant means

i=1;

i 1 manes 1 1=2

i=1 i=i 1// i has already 1 and here we are adding 1 again so result will be 2.

hope you understood.

CodePudding user response:

Lets begin with the first assignment:

i = 1

This creates the variable i and initialize it to the integer value 1.

Then we get to what you seem to have problem understanding:

i = i   1

This statement can be split into two parts:

  1. The addition
  2. The assignment

The addition i 1 will take the current values of the variable i, which is 1, and add the value 1 to that. In essence the expression i 1 is the same as 1 1.

The result of the addition will be 2. And this result is then assigned to the variable i, making the value of i be equal to 2.

You then print the (new) current value of i:

print(i)

This will of course print the value 2.

  • Related