usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

Simple Code for Listing Even Numbers in Python - Fun Exercise for Young Students



What are Even Numbers? | Maths Explanation for Python Kids

Hello pupils, what are even numbers?
Answer:
Even numbers are numbers that are divisible by 2.

They include:

2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, ...

Considering how simple and straight-forward even numbers are, writing a Python code for even numbers serves as a great way to introduce our Mathematics educational activities for young learners.
Well then, let's see how we can write a programming code to make our computer list a set of even numbers in the Python language, between a given range of values. Bear in mind, we use only a loop and a simple conditional statement for the Python code.

Create a new Python Class File; call it Arithmetic.py.
Create a new Python Module File; call it evenNumbers.py.

Type out the adjoining Python code that lists even numbers.


How to run Python Codes

Run the code from the cmd shell with the command: cd ~/Documents/usingMaths -- to navigate to the folder where you saved your files;
python Arithmetic.pl


So! Python Fun Practice Exercise - List Even Numbers

As a fun practice exercise, feel free to try out your own boundary values, and see how the Python code lists the even numbers between those boundary values.







Python Code for Even Numbers - Module File.

# Sure enough this is a module

# define a class
class EvenNumerals:
    
    ###
     # Our constructor.
     # @param alpha - for the start value
     # @param omega - for the end value
     ##
    def __init__(self, alpha, omega):
        self.start = alpha
        self.stop = omega
        self.result = [] # list to hold our answers

    # Returns an list of the desired set of even numbers
    def prepResult(self):
        # Loop from start to stop and rip out even numbers;
        self.i = 0
        while self.start <= self.stop:
            if self.start % 2 == 0: # modulo(%) is explained later
                self.result.append(self.start)
                self.i += 1
                
            self.start = self.start + 1 # increase start by 1
            
        return self.result


Python Code for Even Numbers - Main Class Code.

#!/usr/bin/python
from EvenNumbers import EvenNumerals

# Use the even number module/class
lower_boundary = 1
upper_boundary = 100
even_list = EvenNumerals(lower_boundary, upper_boundary)
answer = even_list.prepResult()
print("Even numbers between", lower_boundary, "and", upper_boundary, "are:\n", answer)


print("\n\n")




<< PreviousNext >>