Home
About Us Privacy Policy
 

OPERATORS IN PYTHON PART 2

ADVERTISEMENT

Beginner Operators II



Bitwise Operator

As we have covered that Python is a high-level language that provides an abstraction to handle data. However, there are instances when the manipulation has to be on "bit-level." Before explaining bitwise operators, let's understand the fundamental unit of information in a computer, i.e., a bit. Electronic systems work on "binary" data, meaning 0 and 1, much like boolean data-type but at the most basic level with no abstraction. The two values, also known as states, signify the presence and absence of data represented by 1 and 0.

Every piece of information ever recorded, transmitted, and manipulated comprises a string of 1's and 0's; this includes textual data, numbers, video files, images, software programs. In particular instances, information needs to be manipulated at the bit level to achieve the desired results. Notable examples include video and image editing, where the setting of certain bits could result in the representation of different pixels values. Have you ever wondered how adding a color filter to your images works? That's how! Bitwise operators.


ADVERTISEMENT

'Setting' refers to 'changing the state' of individual bits in a byte. A sequence of eight bits together is known as a byte.

Although we can manipulate bits, to do so, we have to operate on bytes. It's impossible to work on bits without storing them in a byte.

Even though Python is a high-level language, it allows the programmer to manipulate the most fundamental unit of information, i.e., bits.

Here are the following bitwise operators provided by Python:

Operator Description Example Output
& The Logical And operator will set bit to 1 if both the bits are 1.
print(3 & 1)
1
| The Logical Or operator will set bit to 1 if either of the bit is 1 .
print(2 | 1)
3
The Logical Xor(Exclusive Or) operator will set bit to 1 if only 1 of the bit is 1.
print(2 ^ 1)
3
~ The Logical Inverse operator will inverse all bits, i.e., set 0's to 1 and 1's to 0's.
print(~8)
-9
<< The Left-Shift Operator is used to shift the bits to the left by the specified count.
print(1 << 3)
8
>> The Right-Shift Operator is used to shift the bits to the right by the specified count.
print(8 >> 3)
1

A single character in the ASCII character set is of one byte.

# Convert ASCII characters from Uppercase to lowercase by manipulating a single bit.

A = 'A'
# Convert the character into ASCII numeric representation
A = ord(A)
A = A | 32   # 0010 0000
a = chr(A)
print(a)

a

Let's discuss what happened.

Here is the binary representation of the number 65, which represents 'A' (uppercase 'A') in the ASCII character set.

Bit indexes start from 0.

Bit-Index      7 6 5 4 3 2 1 0
'A' = 65 =      0 1 0 0 0 0 0 1
'a' = 97 =      0 1 1 0 0 0 0 1
32 =              0 0 1 0 0 0 0 0

As you can extrapolate, the index 5(counted from 0) is set to 0 in 'A' and is set to 1 in 'a'. Armed with this valuable information, we can convert to and from uppercase to lowercase and vice-versa.

Here is an example of converting from lowercase to uppercase.

# Converting from lowercase to uppercase
a = ord('a')
A = a ^ 32     
A = chr(A)
print(A)

A


ADVERTISEMENT

Compound Operators

Compound operators are shortcut operators for performing arithmetic and logical operations. It performs the relevant operation and assigns the resulting value back to the variable itself.

Before delving upon compound operators, we must first have a look at a few examples.

a = 8                  # 1
a = a * 10             # 2
a = a // 2             # 3
b = a // 2             # 4
b = b << 2             # 5
c = a | b              # 6
c = c >> 1             # 7

print(a, b, c)   # 40, 80, 60

40, 80, 60

Statements 2, 3, 5, 7 are verbose as we have to explicitly mention the name of the variables multiple times to perform operations. Python allows you to shorten the syntax of eligible expressions for readability and productivity.

Hence, we can write statements 2, 3, 5, 7 as following and achieve the same output.

a *= 2
a //= 2
b <<= 2 
c >>= 1

You will rarely see any professionally written code not using compound operators for relatively simple operations. The compound can be used for every operator except for Identity and Membership operators, which will be covered next.

Here is the table of all eligible compound operators:

Operator Description Example Output
+= The Compound Addition Operator is used to add a value to an existing variable.
x = 7; x += 1; print(x)
8
-= The Compound Subtraction Operator is used to subtract a value from an existing variable.
x = 9; x -= 1; print(x)
8
*= The Compound Multiplication Operator is used to multiply a value to an existing variable.
x = 2; x *= 4; print(x)
8
/= The Compound Division Operator is used to divide an existing variable by a value.
x = 9; x /= 2; print(x)
4.5
%= The Modulus Operator is used to perform modulus on an existing variable by a value.
x = 9; x %= 2; print(x)
1
//= The Floor Division Operator is used to perform a floor division on an existing variable by a value.
x = 9; x //= 2; print(x)
4
**= The Exponential Division Operator is used to perform exponential on an existing variable by a value.
x = 2; x **= 3; print(x)
8
&= The Bitwise And Operator is used to perform Bitwise And on an existing variable and re-assign the result back.
x = 3; x &= 1; print(x)
1
|= The Bitwise Or Operator is used to perform Bitwise Or on an existing variable and re-assign the result back.
x = 2; x |= 1; print(x)
3
^= The Bitwise Xor Operator is used to perform Bitwise Xor on an existing variable and re-assign the result back.
x = 3; x ^= 1; print(x)
2
<<= The Bitwise Left-Shift Operator is used to perform Bitwise Left-Shift on an existing variable and re-assign the result back.
x = 4; x <<= 1; print(x)
8
>>= The Bitwise Right-Shift Operator is used to perform Bitwise Right-Shift on an existing variable and re-assign the result back.
x = 4; x >>= 1; print(x)
2


ADVERTISEMENT

Identity Operators

Since Python is an object-oriented language, almost everything is an object, and there are situations when you might want to test equality between two instances.

In data types, we learned about the type() method to determine the underlying characteristics of the variable.

Both the is and is not operators return boolean values only.

credit_score = 801
is_credit_excellent = credit_score >= 800
is_credit_good = credit_score >= 740 and credit_score <= 799
print(type(is_credit_excellent) is bool) # TRUE
print(type(is_credit_good) is not int) # TRUE

True
True

Python provides two identity operators:

  • is
  • is not

The is operator

This operator is useful for testing the same identities.

print(type(is_credit_excellent) is bool) # TRUE


The is not operator.

The is not operator is used for testing the objects of different identities.

print(type(is_credit_good) is not int) # TRUE

The identity operators are helpful when dealing with instances of class objects. We will touch classes and identity operators later.


Membership Operator

We have learned about individual variables and values, but we can also store values in a sequence together in lists and tuples. We will cover them in detail later, but to demonstrate the usage of membership operators, we'll discuss them as well.

Python provides the following membership operators:

  • in
  • not in

Both the in and not in operators return only boolean values.

# Even numbers
even_numbers = [0, 2, 4, 6, 8]
print(2 in even_numbers)  # TRUE
print(10 in even_numbers)  # FALSE
print(3 not in even_numbers)  # TRUE
print(5 in even_numbers)   # FALSE

True
False
True
False

As you can see, using the in and not in operators, we can verify the representation of the value in a sequence. It is advantageous when dealing with textual data and numerical computing with large data sets.

We will revisit Membership operators when covering Strings, Lists, Tuples in Python.


Conclusion

In this chapter, we learned about the importance of operators and what they do, different types of operators, multiple uses of identity, and membership operators, and their examples.


ADVERTISEMENT



All product names, logos, and brands are property of their respective owners.