How to Check If a Number Is Odd in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a number is odd in Python. The lab focuses on using the modulo operator (%) to determine if an integer is odd by checking if it's evenly divisible by 2.

You'll start by defining odd numbers and applying the modulo operator to a sample number. Then, you'll modify the code to test different numbers and observe the output, solidifying your understanding of how the modulo operator works in identifying odd and even numbers. Finally, you will validate the input type to ensure the code handles non-integer inputs gracefully.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") 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/variables_data_types -.-> lab-559552{{"How to Check If a Number Is Odd in Python"}} python/numeric_types -.-> lab-559552{{"How to Check If a Number Is Odd in Python"}} python/type_conversion -.-> lab-559552{{"How to Check If a Number Is Odd in Python"}} python/conditional_statements -.-> lab-559552{{"How to Check If a Number Is Odd in Python"}} python/catching_exceptions -.-> lab-559552{{"How to Check If a Number Is Odd in Python"}} end

Define Odd Numbers

In this step, you will learn how to define odd numbers in Python. Odd numbers are integers that cannot be evenly divided by 2. You'll use the modulo operator (%) to determine if a number is odd.

First, let's create a Python file named odd_numbers.py in your ~/project directory using the VS Code editor.

~/project/odd_numbers.py

Now, open odd_numbers.py in the editor and add the following code:

number = 7
if number % 2 != 0:
    print(number, "is an odd number")
else:
    print(number, "is not an odd number")

In this code:

  • We assign the integer 7 to the variable number.
  • We use the modulo operator (%) to get the remainder when number is divided by 2.
  • If the remainder is not equal to 0, the number is odd, and we print a message indicating that.
  • Otherwise, the number is even, and we print a different message.

Save the odd_numbers.py file.

Next, run the script using the python command in the terminal:

python odd_numbers.py

You should see the following output:

7 is an odd number

Now, let's modify the odd_numbers.py file to check if a different number, say 4, is odd. Open odd_numbers.py in the editor and change the value of the number variable:

number = 4
if number % 2 != 0:
    print(number, "is an odd number")
else:
    print(number, "is not an odd number")

Save the odd_numbers.py file and run it again:

python odd_numbers.py

You should now see the following output:

4 is not an odd number

This demonstrates how to define and check for odd numbers in Python using the modulo operator.

Apply Modulo Operator

In this step, you will deepen your understanding of the modulo operator (%) and explore its applications in determining odd and even numbers. The modulo operator returns the remainder of a division. This is particularly useful for identifying odd and even numbers because any even number divided by 2 has a remainder of 0, while an odd number has a remainder of 1.

Let's modify the odd_numbers.py file you created in the previous step to accept input from the user and then apply the modulo operator.

Open odd_numbers.py in the VS Code editor and replace the existing code with the following:

number = int(input("Enter an integer: "))

if number % 2 == 0:
    print(number, "is an even number.")
else:
    print(number, "is an odd number.")

Here's a breakdown of the code:

  • input("Enter an integer: "): This prompts the user to enter an integer. The input() function always returns a string, so we need to convert it to an integer.
  • int(...): This converts the string input to an integer.
  • number % 2 == 0: This checks if the remainder when number is divided by 2 is equal to 0. If it is, the number is even.
  • The if and else statements then print the appropriate message based on whether the number is even or odd.

Save the odd_numbers.py file.

Now, run the script using the python command in the terminal:

python odd_numbers.py

The script will prompt you to enter an integer. Enter 10 and press Enter:

Enter an integer: 10

You should see the following output:

10 is an even number.

Run the script again and enter 15:

python odd_numbers.py
Enter an integer: 15
15 is an odd number.

This demonstrates how to use the modulo operator to determine if a number entered by the user is odd or even. The modulo operator is a fundamental tool in programming and is used in various applications beyond just checking for odd and even numbers.

Validate Input Type

In this step, you will learn how to validate the input type to ensure that the user enters an integer. This is important because the int() function will raise a ValueError if the input cannot be converted to an integer (e.g., if the user enters text).

To handle potential errors, you'll use a try-except block. This allows you to gracefully handle exceptions and prevent your program from crashing.

Open odd_numbers.py in the VS Code editor and replace the existing code with the following:

try:
    number = int(input("Enter an integer: "))
    if number % 2 == 0:
        print(number, "is an even number.")
    else:
        print(number, "is an odd number.")
except ValueError:
    print("Invalid input. Please enter an integer.")

Here's a breakdown of the code:

  • try:: This block contains the code that might raise an exception.
  • number = int(input("Enter an integer: ")): This line attempts to convert the user's input to an integer. If the input is not a valid integer, a ValueError will be raised.
  • if number % 2 == 0: and else:: These lines are the same as in the previous step, checking if the number is even or odd.
  • except ValueError:: This block catches the ValueError exception if it is raised in the try block.
  • print("Invalid input. Please enter an integer."): This line prints an error message if the user enters invalid input.

Save the odd_numbers.py file.

Now, run the script using the python command in the terminal:

python odd_numbers.py

The script will prompt you to enter an integer. Enter abc and press Enter:

Enter an integer: abc

You should see the following output:

Invalid input. Please enter an integer.

Run the script again and enter 7.5:

python odd_numbers.py

You should see the following output:

Invalid input. Please enter an integer.

Run the script again and enter 11:

python odd_numbers.py
Enter an integer: 11
11 is an odd number.

This demonstrates how to validate the input type and handle potential errors using a try-except block. This is a crucial skill for writing robust and user-friendly programs.

Summary

In this lab, you learned how to define odd numbers in Python and use the modulo operator (%) to determine if a number is odd or even. You created a Python script, odd_numbers.py, and used the modulo operator to check the remainder when a number is divided by 2. If the remainder is not 0, the number is identified as odd; otherwise, it's even.

You practiced modifying the script with different numbers and observing the corresponding output, solidifying your understanding of how the modulo operator works in identifying odd and even numbers.