0

What does I=I+1 do?!

i = 1 while i <=5: print(i) i = i + 1 print("Finished!") In this code, when I=I+1 exists, It prints 12345 When the code doesn't exist It prints 1111111111 I don't understand what I=I+1 do!!! Also don't understand that logic :/ A number= that number + 1?:/ how is it possible?😐

5th Jun 2020, 10:08 AM
Victor Bro
Victor Bro - avatar
6 Antworten
+ 3
i=i+1 or u can write it like this too i+=1 means in each turn increase the value of i by 1 with saving the old value in your code first turn i=1 as i <=5 then print the value of i and increase it by 1 second turn i=1+1=2 2<=5 true the code will print the value of i which is 2 and increase it by 1 third turn i=2+1=3 3<=5 true the same thing will happen here like the previous step fourth turn i=3+1=4 4<=5 true the same thing will happen here like the previous step fifth turn i=4 +1= 5 5<=5 true the same thing will happen here like the previous step sixth turn i=5+1=6 6<=5 false the while loop will be breaked At finaly print Finished 1 2 3 4 5 Finished if u delete the condtion i=i+1 The condition inside the while loop will be true always which make the code print infinite 1 u can stop the program by click ctrl+c as this effect on the memory of the device
5th Jun 2020, 10:24 AM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 2
i = 1 You start with a value of i, which is equal to 1 while i < 5: Now there is a while loop which will continue until the condition is met. Your condition is that i<5. print(i) As your code iterates through the while loop, it will produce the result of each iteration. i = i+1 Now for the fun part. Your loop starts with value i=1 This is less than 5, So print(i) => 1 i = i+1 => 1+1 => 2 Value i is now 2 Loop starts again because 2 < 5 print(i) => 2 i = i+1 => 2+1 => 3 Value is now 3..... This pattern continues until 5 is achieved, the while loop returns True and stops the iteration. Without i = i+1, your while loop will never stop because value i will never grow beyond 1 Another way of writing i = i + 1 is: i +=1
5th Jun 2020, 10:26 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
i = i+1 will add 1 to the variable i.(if i is 1, (i=i+1) =2) If you take i = i+1 from the code, the while loop will never stop, because i will never be bigger or equal to 5, so it will print the i value (1) forever. I hope it was helpful. If not, let me know
5th Jun 2020, 10:20 AM
Alexandre
Alexandre - avatar
0
In this question " l " is a variable. In this case by default " l " value is 0. l = l +1; --> it means that : l = 0 + 1; Therefore, now the value of " l" is 1. Next time the value of "l" Will be l = 1+ 1 Now value of " l " is 2. Use same logic for others also.
5th Jun 2020, 10:19 AM
Omkar Kamat
Omkar Kamat - avatar
0
The value of i is bigger for 1
5th Jun 2020, 11:54 AM
CodeFu
CodeFu - avatar