A number is even if it is perfectly divisible by 2. When the number is divided by 2, we use the remainder operator %
to compute the remainder. If the remainder is not zero, the number is odd.
Source Code
# Python program to check if the input number is odd or even.
# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.
num = int[input["Enter a number: "]]
if [num % 2] == 0:
print["{0} is Even".format[num]]
else:
print["{0} is Odd".format[num]]
Output 1
Enter a number: 43 43 is Odd
Output 2
Enter a number: 18 18 is Even
In this program, we ask the user for the input and check if the number is odd or even. Please note that { }
is a replacement field for num
.
Python Program to Check if a Number is Odd or Even
Odd and Even numbers:
If you divide a number by 2 and it gives a remainder of 0 then it is known as even number, otherwise an odd number.
Even number examples: 2, 4, 6, 8, 10, etc.
Odd number examples:1, 3, 5, 7, 9 etc.
See this example:
Output:
Feedback
- Send your Feedback to [email protected]
Help Others, Please Share
How would you output 0,2,4,6,8,10?
We do not care about formatting, it may be in a row, in a list, or in a column.
1. With just one print
The simplest way is:
print[0,2,4,6,8,10]
2. For loop
The first method that comes into my mind:
for i in range[0,11,2]:
print[i]
3. For and %
for i in range[11]:
if i % 2 == 0:
print[i]
4. Generators and %
print[[i for i in range[11] if i%2 == 0]]
5. Generators and Binary
Here we check the binary representation of a number and check if the last digit is 1
print[[i for i in range[11] if bin[i][-1] == "0"]]
6. Bitwise AND
Bitwise & with 1 gives 0 if the last bit is 0, and 1 otherwise
print[[i for i in range[11] if i&1 == 0]]
7. Bitwise OR
This one is tricky: we make the last bit always a 1, so we always have an odd number. Later, we simply subtract 1 to get even numbers
and get rid of duplicates with the set
function.
print[set[[[i|1]-1 for i in range[11]]]]
8. Multiplication
print[[i*2 for i in range[6]]]
9. Iterators [yield]
def evens[]:
i = 0
while True:
yield i
i += 2iterator = evens[]
for i in range[6]:
print[iterator.__next__[]]
10. Multiplication and Lambda
double = lambda x: x * 2
for i in range[6]:
print[double[i]]
11. Recursion
def print_evens[i]:
if i > 10:
return
print[i]
print_evens[i+2]print_evens[0]
12. Random
import random
random.seed[99353]
for i in range[6]:
print[random.randint[0,i*3]]
13. Sine
import math
for i in range[6]:
print[int[math.sin[i/5]*12]]
14. Another one with binary
for i in range[11]:
if int[bin[1365][2:][i]]:
print[i]
15. Object-oriented programming
Let’s simply extend the int
class:
class num[int]:
def even[self]:
return self%2 == 0for i in range[11]:
if num[i].even[]:
print[i]
These are some of the most frequently used ways to output even numbers. Which one would you prefer? I personally always go for the one with randoms, this way my colleagues never realize what is happening there.