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:
- The input(): function is used to ask the user to enter an integer.
- The int() function: is then used to convert the input to an integer data type.
- The if instruction: checks whether the number is even or odd using the modulo operator %.
- If the remainder: of the number divided by 2 is 0, the number is even. Otherwise, it is odd.
- If the number is even: the program displays a message indicating that the number is even, along with the original number.
- 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
[…] Exercise 5 || Solution […]