Find the parity of a number using Python

In this article, we discuss how to find the parity of the number using Python. Parity means a count of the number of 1’s in a binary value of a digit. Mainly, there are two types of parity. There are mentioned below:

  • Even parity
  • Odd parity

Find the parity of a number using Python

Even parity:

In this parity, we count the no of one’s in the binary value of the given digit. If the number of ones in the binary value is even then the parity value is zero. If the number of ones is odd then the parity value is even.

For Example:

n=int(input())
c=0
n=bin(n)
for i in n:
    if(i==1):
        c=c+1
    else:
        pass
if(c%2!=0 and c==0):
    print('1')
else:
    print('0')


        

As a result:

5
0

Odd parity:

In this parity, as same as even parity we count the number of ones. But there is an odd number of ones than the parity value is zero. If there is even a number of ones in the binary number then the parity value is one.

n=int(input())
c=0
n=bin(n)
for i in n:
    if(i==1):
        c=c+1
    else:
        pass
if(c%2=0):
    print('1')
else:
    print('0')
5
1

 

In this article ‘Find the parity of the number using Python’, the above examples are some of the methods used to find the parity of the number.

Leave a Reply