+ 2
Got this one on quiz ( the answer is 2359)
i=1 while i<=10: print(i+1) i*=2 # I need explanation, didn't understand the code
6 Respostas
+ 7
"""
<i> = 1
Repeat while <i> <= 10
# iteration 1. <i> = (1)
print <i> + 1 # output 2
<i> *= 2 # <i> becomes (2)
# iteration 2. <i> = (2)
print <i> + 1 # output 3
<i> *= 2 # <i> becomes (4)
# iteration 3. <i> = (4)
print <i> + 1 # output 5
<i> *= 2 # <i> becomes (8)
# iteration 4. <i> = (8)
print <i> + 1 # output 9
<i> *= 2 # <i> becomes (16)
When we get here, the condition <i> <= 10 no longer satisfies, and the loop cease repetition.
However, to see such output, you'd have to specify `end = ""` argument to customize the end-of-line character used by print() function. If you didn't do it, you'll see 2, 3, 5 and 9 be printed on separate lines.
"""
i = 1
while i <= 10:
print( i + 1, end = "")
i *= 2
+ 2
i is 1,2,4,8 each time through the loop
+ 2
✓Iteration 1
Initially i is 1
So now in while loop
Condition satisfies as 1<=10
So it will print 2(because i is 1 so 1+1=2)
Now i value changes as i=i*2
I.e i=1*2=2
✓Iteration 2
Now i is 2
So now in while loop
Condition satisfies as 2<=10
So it will print 3(because i is 2 so 2+1=3)
Now i value changes as i=i*2
I.e i=2*2=4
✓Iteration 3
Now i is 4
So now in while loop
Condition satisfies as 4<=10
So it will print 5(because i is 4 so 4+1=5)
Now i value changes as i=i*2
I.e i=4*2=8
✓Iteration 4
Now i is 8
So now in while loop
Condition satisfies as 8<=10
So it will print 2(because i is 1 so 8+1=9)
Now i value changes as i=i*2
I.e i=8*2=16
✓Iteration 4
Now i is 16
So now in while loop
Condition doesn't satisfies as 16>10
So it will terminate out.
+ 1
Hi!
Don’t use uppercase letters in ’while’ and ’print’. Also the answer became:
1
2
4
8
(Not 2359.)
i *= 2 means i = i * 2
So the prcocess in the while loop become:
[ head ] [ body ]
i = 1 < 10: -> print(1); i = 1*2
i = 2 < 10: -> print(2); i = 2*2
i = 4 < 10: -> print(4); i = 4*2
i = 8 < 10: -> print(8); i = 8*2
i = 16 !< 10: -> stop loop!
0
Start i=1
The while loop will iterate as the value of i is <=10
And print(i+1) that is 1+1 = 2
Now i will increment as i = i*2 every time
So according to this iteration the values of i after every incrementation
i = 1,2,4,8
And will print i+1 that is 2359
- 1
well when you made a loop with while and the condition stops at10 according to youre code the i wil accrese until it reach 10 and then the i will be multiple 2 until it reach 10 if the number it reached isnt 10 it will asign the number before it
so according to youre code the output is:
0
1
2
3
4
5
6
7
8
9
and the i *=2 wont output untill you print it but it will be like this
0
2
4
6
8
10