How to Check If a Number Is Even in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you'll learn how to determine if a number is even or odd in Python. We'll start by understanding the fundamental concepts of even and odd numbers, defining them as integers divisible by 2 with a remainder of 0 (even) or 1 (odd).

The lab then guides you through using the modulo operator (%) to check for evenness. You'll create a Python script that utilizes an if statement and the modulo operator to determine and print whether a given number is even or odd. The lab includes step-by-step instructions for creating the script in VS Code and running it from the terminal.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/BasicConceptsGroup -.-> python/type_conversion("Type Conversion") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("Catching Exceptions") subgraph Lab Skills python/numeric_types -.-> lab-559548{{"How to Check If a Number Is Even in Python"}} python/type_conversion -.-> lab-559548{{"How to Check If a Number Is Even in Python"}} python/conditional_statements -.-> lab-559548{{"How to Check If a Number Is Even in Python"}} python/catching_exceptions -.-> lab-559548{{"How to Check If a Number Is Even in Python"}} end

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:

  1. Open the VS Code editor in the WebIDE.

  2. Create a new file named even_odd.py in the ~/project directory.

    ~/project/even_odd.py
  3. 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.

  4. 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
  5. 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")
  6. 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.

Use Modulo Operator

In the previous step, you learned about even and odd numbers and how the modulo operator (%) can be used to determine if a number is even or odd. In this step, we'll dive deeper into the modulo operator and explore its various applications.

Understanding the Modulo Operator

The modulo operator (%) returns the remainder of a division. The syntax is a % b, where a is the dividend (the number being divided) and b is the divisor (the number you are dividing by). The result is the remainder of the division.

Here are some examples:

  • 7 % 2 evaluates to 1 because 7 divided by 2 is 3 with a remainder of 1.
  • 10 % 3 evaluates to 1 because 10 divided by 3 is 3 with a remainder of 1.
  • 15 % 5 evaluates to 0 because 15 divided by 5 is 3 with a remainder of 0.

Applications of the Modulo Operator

The modulo operator has many useful applications in programming, including:

  • Determining Even or Odd: As you saw in the previous step, number % 2 == 0 indicates that number is even, and number % 2 != 0 indicates that number is odd.
  • Wrapping Around: The modulo operator can be used to wrap around a range of numbers. For example, if you have a counter that should cycle through the numbers 0 to 9, you can use the modulo operator to reset the counter to 0 when it reaches 10.
  • Extracting Digits: The modulo operator can be used to extract the last digit of a number. For example, number % 10 returns the last digit of number.

Let's modify the even_odd.py script to get the number from user input and use the modulo operator to check if it's even or odd.

  1. Open the even_odd.py file in the ~/project directory using the VS Code editor.

  2. Modify the code as follows:

    number_str = input("Enter an integer: ")
    number = int(number_str)
    
    if number % 2 == 0:
        print(number, "is an even number")
    else:
        print(number, "is an odd number")

    In this code, we use the input() function to prompt the user to enter an integer. The input() function returns a string, so we use the int() function to convert the string to an integer. Then, we use the modulo operator to check if the number is even or odd, as before.

  3. Run the script using the following command:

    python ~/project/even_odd.py

    The script will prompt you to enter an integer. Enter a number and press Enter. For example:

    Enter an integer: 15

    The script will then output whether the number is even or odd:

    15 is an odd number

    Try running the script with different numbers to see how the modulo operator works.

This example demonstrates how to use the modulo operator with user input to determine whether a number is even or odd. In the next step, we'll add error handling to ensure that the user enters a valid integer.

Ensure the Number Is an Integer

In the previous step, you learned how to use the input() function to get user input and the int() function to convert the input to an integer. However, if the user enters something that is not an integer (e.g., "hello" or "3.14"), the int() function will raise a ValueError exception, causing the program to crash. In this step, we'll add error handling to ensure that the user enters a valid integer.

Error Handling with try-except

Python provides a try-except block to handle exceptions. The code in the try block is executed. If an exception occurs, the code in the except block is executed.

Here's the basic syntax:

try:
    ## Code that might raise an exception
except ValueError:
    ## Code to handle the ValueError exception

If a ValueError occurs in the try block, the code in the except ValueError block will be executed.

Let's modify the even_odd.py script to use a try-except block to handle potential ValueError exceptions.

  1. Open the even_odd.py file in the ~/project directory using the VS Code editor.

  2. Modify the code as follows:

    while True:
        number_str = input("Enter an integer: ")
        try:
            number = int(number_str)
            break  ## Exit the loop if the input is a valid integer
        except ValueError:
            print("Invalid input. Please enter an integer.")
    
    if number % 2 == 0:
        print(number, "is an even number")
    else:
        print(number, "is an odd number")

    In this code, we've added a while True loop that continues to prompt the user for input until a valid integer is entered. Inside the loop, we have a try-except block. The try block attempts to convert the user's input to an integer. If the conversion is successful, the break statement exits the loop. If a ValueError occurs (meaning the user entered something that is not an integer), the except block prints an error message, and the loop continues.

  3. Run the script using the following command:

    python ~/project/even_odd.py

    If you enter a non-integer value, such as "hello", you'll see the following output:

    Enter an integer: hello
    Invalid input. Please enter an integer.
    Enter an integer:

    The script will continue to prompt you for input until you enter a valid integer. Once you enter a valid integer, such as 12, the script will output whether the number is even or odd:

    Enter an integer: 12
    12 is an even number

This example demonstrates how to use a try-except block to handle potential ValueError exceptions when converting user input to an integer. This makes your program more robust and user-friendly.

Summary

In this lab, we explored the fundamental concepts of even and odd numbers, understanding that even numbers are divisible by 2 with a remainder of 0, while odd numbers have a remainder of 1 when divided by 2.

We utilized the modulo operator (%) in Python to determine if a number is even or odd. A simple Python script was created and executed to demonstrate this, checking if the remainder of a number divided by 2 is equal to 0 to identify even numbers.