How to Program for even or odd in python
Published on Aug. 22, 2023, 12:16 p.m.
To check whether a number is even or odd in Python, you can use the %
operator to check whether the remainder of the number divided by 2 is equal to 0. If the remainder is 0, the number is even; otherwise, it is odd. Here is an example program in Python to check whether a number is even or odd:
num = int(input("Enter a number: "))
if num % 2 == 0:
print("The number is even")
else:
print("The number is odd")
In this program, we first prompt the user to enter a number, then we use the int()
function to convert the user input (which is a string by default) to an integer. We then use the %
operator to check whether the remainder of the number divided by 2 is equal to 0. If it is, we print “The number is even”; otherwise, we print “The number is odd”.
You can modify this program to check whether multiple numbers are even or odd by using a loop to iterate over a list of numbers.
To program for even or odd in a loop
To program for even or odd in a loop, you can modify the earlier mentioned code to use a loop to iterate through a list of numbers and check whether each number is even or odd. Here is an example Python program to check whether the numbers from 1 to 10 are even or odd:
for i in range(1, 11):
if i % 2 == 0:
print(i, "is even")
else:
print(i, "is odd")
In this program, we use a for
loop to iterate through the numbers from 1 to 10 (inclusive). For each number, we check whether it is even or odd using the %
operator, and print the appropriate message to the console.
You can modify the range arguments to check a different set of numbers. The range()
function generates a sequence of numbers from the starting value (inclusive) to the ending value (exclusive), with an optional step size between each number.
Note that this program checks each number individually and prints a message for each one. If you simply want to count the number of even or odd numbers in a range, you can use a counter variable instead and increment it for each even or odd number you encounter.