Data types and variables
Operators
Modules and Packages
Conversion Programs
More Code Examples
Cheat Sheet

Python Code Example: Check the Number is Even or Odd

In this simple example, we will examine a Python script that determines whether a given integer is even or odd. The script prompts the user to input an integer and then uses a conditional statement to check the parity of the number. Based on the result, it prints whether the number is even or odd. This example highlights the use of basic input/output functions, conditional statements, and arithmetic operations in Python.

Code Example

x = int(input("Enter a value for x: "))

if x % 2 == 0:
    print("Number " + str(x) + " is even")
else:
    print("Number " + str(x) + " is odd")

Detailed Code Explanation

Input Statement

x = int(input("Enter a value for x: "))

This line prompts the user to enter a number, which will be stored in the variable x.

Step-by-Step Explanation

  • input("Enter a value for x: "): Displays the message “Enter a value for x:” and waits for the user to input a value.
  • int(...): Converts the user input (a string) to an integer and assigns it to the variable x.

Conditional Statement

if x % 2 == 0:
    print("Number " + str(x) + " is even")
else:
    print("Number " + str(x) + " is odd")

This block of code checks whether the number stored in x is even or odd and prints the appropriate message.

Step-by-Step Explanation

  • x % 2 == 0: The modulo operator % calculates the remainder of x divided by 2. If the remainder is 0, it means x is an even number.
  • if x % 2 == 0:: If the condition x % 2 == 0 is true, the code inside the if block is executed.
    • print("Number " + str(x) + " is even"): Constructs a string that includes the value of x and the message “is even”, then prints it to the console.
  • else:: If the condition x % 2 == 0 is false (meaning x is not even), the code inside the else block is executed.
    • print("Number " + str(x) + " is odd"): Constructs a string that includes the value of x and the message “is odd”, then prints it to the console.