Ask coding questions

← Back to all posts
how to make a 'for' loop to print all even numbers between 0-100
DhanikaMalik

hi i cant figure how to make a 'for' loop in python to print all even numbers between 0-100

Voters
DhanikaMalik
Comments
hotnewtop
JohnjiRomanji

So for loops can loop through a list. The range() function returns a list of numbers in your range (you can try it and see), but it is not inclusive. So, to generate a list of numbers from 1-100, you would do range(0, 101).
Now you have a list that looks something like this:

Your next step is to loop, so using a for loop, you would do this:

Now if you replaced #stuff goes here with print(i) it would print every number in the list from 1 to 100, but you only want even numbers.
We can check for even numbers using modulus (%).
The modulus returns a the remainder of an integer division, so 5 % 2 is 1 because 5 divided by 2 is 2 remainder 1.
Now we can make an if statement to make your loop only print if the number in the list is even and thus returns a 0 when it is modulus divided by 2.

Our final code is:

DhanikaMalik

@JohnjiRomanji thanks. it helped a lot!!!!

RYANTADIPARTHI

do this.

GameDev46

Just do: