+ 2
This is a easy question but I always get wrong answers can anybody pls help me.
The question is "Print all the even numbers from 0 to 10 using while loop". This was my code x = 0 while ((x / 2) == 0) <=10: print (x) x += 1
4 Réponses
+ 4
sPaRkLe , Here are 2 other approaches:
# basic approach: using for loop with range() - this avoids using a counter variable:
for num in range(10 + 1):
if num % 2 == 0:
print(num)
# advanced approach: using a comprehension:
print([num for num in range(10 + 1) if num % 2 == 0])
-> your own code will not run properly:
- because the increment of counter variable x is outside the loop
- the while condition x / 2 == 0 is only valid for the first x value (0), but not for the next x value which is 1. So the loop will be terminated after one cycle.
+ 3
Thank you everyone for the answers, they really helped me
+ 2
sPaRkLe
Try this code
https://code.sololearn.com/c0lFMhZtmYFA/?ref=app
+ 2
You should probably read the lesson about while loop in python course and understand how it works. After while you write only the loop condition (x<=10). Increment should be done every time, so has to be indented