Programmers can generate numbers in Python any number of ways. While random number generation exists as a built in function, a programmer may want to build lists of specific, recurring patterns of numbers. Or, rather, a programmer wishes to use a number generation algorithm as an input function. Whatever the case may be, generating number patterns (such as the odd numbers) requires only a loop and the math to generate the pattern.
Video of the Day
Set up the generator loop. In the IDE, enter the following code:
i=0 >>>while i < 10:
This sets up the generating loop to run for ten iterations. This means it will print all odd numbers between zero and nine. In order to run a longer generator, enter a higher value for the while loop condition.
Write the generator code, following the while loop (Remember that in Python, indents separate blocks of code, so the "if" statement should be indented once after the "while," and the "print" statement once after the "if"):
i=10 >>>while i < 10: ... if i % 2 != 0: ... print i ... i = i + 1
The loop, for every iteration, will check the modulo of i and the constant two. The modulo operator simply returns the remainder of a number divided by another number. So, if a number divided by two has no remainder, this means it is an even number. If it has a remainder, it is odd, and the loop prints that value of i. It then adds one to the value of i and moves to the next iteration.
Print the numbers. After the last line is entered, hit enter to run the generator. The output should appear as follows:
i=10 >>>while i < 10: ... if i % 2 != 0: ... print i ... i = i + 1 1 3 5 7 9 >>>