+ 1

list = list(range(101)) i = 0 while i <= 100: m = i%2 if m == 0: index = list[i] print(index) i = i + 1

Wanna print even using while loop

16th Apr 2019, 5:56 AM
ALBERT SAURAV
ALBERT SAURAV - avatar
9 odpowiedzi
+ 5
HonFu - that‘s perfect! Reduced to what it should do and has a phantastic readibility.
16th Apr 2019, 11:06 AM
Lothar
Lothar - avatar
+ 4
hi Albert, you can also do this: for i in range(1, 101): if i % 2 == 0: print(i, end = ', ') result is: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, ... 100
16th Apr 2019, 8:56 AM
Lothar
Lothar - avatar
+ 4
hi Albert & Smith, your code is working, but i think we don’t need the range stuff. i = 0 while i <= 100: if i%2==0: print(i) i += 1
16th Apr 2019, 6:07 PM
Lothar
Lothar - avatar
+ 3
Your line i = i + 1 is only executed if m == 0 because it belongs to the block of that condition. So as soon as you meet an odd number, i stays what it is and your loop runs forever. Just change the indentation of that line to the indentation of the while block and your code runs.
16th Apr 2019, 6:47 AM
HonFu
HonFu - avatar
+ 2
list = list(range(102)) i = 0 while i <= 100: if i%2==0: #m = i%2 #if m == 0: #index = list[i] print(list[i]) #print(index) i += 1
16th Apr 2019, 4:17 PM
Smith Welder
Smith Welder - avatar
+ 2
While spending too much memory, generator better for u in ( i for i in range(100) if i% 2==0): print(u)
16th Apr 2019, 6:40 PM
Smith Welder
Smith Welder - avatar
+ 1
It isnt working ...i am stuck
16th Apr 2019, 5:56 AM
ALBERT SAURAV
ALBERT SAURAV - avatar
+ 1
Or just this. ;-) print(*range(0,101, 2))
16th Apr 2019, 10:23 AM
HonFu
HonFu - avatar
+ 1
Lothar, the problem is that Python just provides it to you. It's like clicking a button. Although in real life you would probably choose the simplest solution whenever possible, you can hardly say you've written any code, or have gotten any practice. So from a training perspective it can be worthwhile to do it all with your own hands, practicing how to set up all these loops correctly in order to get the desired outcome.
16th Apr 2019, 11:11 AM
HonFu
HonFu - avatar