+ 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
9 Réponses
+ 5
HonFu - that‘s perfect! Reduced to what it should do and has a phantastic readibility.
+ 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
+ 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
+ 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.
+ 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
+ 2
While spending too much memory, generator better
for u in ( i for i in range(100) if i% 2==0):
print(u)
+ 1
It isnt working ...i am stuck
+ 1
Or just this. ;-)
print(*range(0,101, 2))
+ 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.