How to Iterate Only Even Numbers in "For Loop" in Python
In most programming languages, the syntax of the for loop allows the programmer to directly specify where the loop begins, where it ends and what rules should be followed to proceed through the loop. However, in Python, loops always proceed from a list and move through every item in the list. In order to loop according to another rule, such as looping over only even numbers, you must use the range command.
Instructions
-
-
1
Open the IDLE Python debugger.
-
2
Type the following command:
for x in range(0, 20, 2):
print (x);The range command is key. The first argument (0) is where the loop begins. The second (20) is the test condition. When the counter reaches "20," the loop stops. The final argument is how much to add to the counter with each iteration. Because you want only even numbers, you should put "2."
-
-
3
Press "F5" on your keyboard to test the program.
-
1
Tips & Warnings
Python 2.5 has a function, xrange, which achieves the same results with less of a performance penalty. However, it was removed in Python 3.0.