Exercise 5

Write a Python algorithm which asks the user to enter their integer number and to display it if this number is even or odd.

Solution

# ask user to enter an integer
number = int(input("Enter an integer: "))

# check if the number is even or odd
if number % 2 == 0:
    print(f"{number} is even.")
else:
    print(f"{number} is odd.")

Explanation:

  1. The input(): function is used to ask the user to enter an integer.
  2. The int() function: is then used to convert the input to an integer data type.
  3. The if instruction: checks whether the number is even or odd using the modulo operator %.
  4. If the remainder: of the number divided by 2 is 0, the number is even. Otherwise, it is odd.
  5. If the number is even: the program displays a message indicating that the number is even, along with the original number.
  6. If the number is odd: the program displays a message indicating that the number is odd, along with the original number.

Example Output:

Enter an integer: 7
7 is odd.

Example Output:

Enter an integer: 20
20 is even.




 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 5: odd or even number in Python”

Leave a Reply