Learn About Even and Odd Numbers
In this step, we'll explore the fundamental concepts of even and odd numbers. Understanding these concepts is crucial for various programming tasks, including data validation, algorithm design, and game development.
What are Even Numbers?
An even number is an integer that is exactly divisible by 2. This means that when you divide an even number by 2, the remainder is always 0. Examples of even numbers include: 2, 4, 6, 8, 10, and so on.
What are Odd Numbers?
An odd number is an integer that is not exactly divisible by 2. When you divide an odd number by 2, the remainder is always 1. Examples of odd numbers include: 1, 3, 5, 7, 9, and so on.
How to Determine if a Number is Even or Odd
In programming, we often need to determine whether a given number is even or odd. Python provides a simple way to do this using the modulo operator (%
). The modulo operator returns the remainder of a division.
For example, 7 % 2
evaluates to 1 because when you divide 7 by 2, the remainder is 1. Similarly, 8 % 2
evaluates to 0 because when you divide 8 by 2, the remainder is 0.
Let's create a simple Python script to illustrate this:
-
Open the VS Code editor in the WebIDE.
-
Create a new file named even_odd.py
in the ~/project
directory.
~/project/even_odd.py
-
Add the following code to the even_odd.py
file:
number = 10
if number % 2 == 0:
print(number, "is an even number")
else:
print(number, "is an odd number")
This code first assigns the value 10 to the variable number
. Then, it uses an if
statement to check if the remainder of number
divided by 2 is equal to 0. If it is, the code prints that the number is even. Otherwise, it prints that the number is odd.
-
Run the script using the following command in the terminal:
python ~/project/even_odd.py
You should see the following output:
10 is an even number
-
Now, change the value of number
in the even_odd.py
file to 7:
number = 7
if number % 2 == 0:
print(number, "is an even number")
else:
print(number, "is an odd number")
-
Run the script again:
python ~/project/even_odd.py
You should now see the following output:
7 is an odd number
This simple example demonstrates how to use the modulo operator to determine whether a number is even or odd in Python. In the next steps, we'll build upon this foundation to create more complex programs.