Introduction
In this lab, you will gain a comprehensive understanding of various operators in Python, a fundamental concept for writing effective code. We will explore and practice using arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators.
Through hands-on exercises using the integrated VS Code editor and terminal, you will learn how to perform calculations, make comparisons, assign values, combine conditions, manipulate bits, check for membership, and compare object identities. By the end of this lab, you will be proficient in using these operators to build more complex and functional Python programs.
Explore Arithmetic and Comparison Operators
In this step, we will explore the fundamental arithmetic and comparison operators in Python. These operators are essential for performing calculations and making decisions in your programs. The lab environment has already created a file named operators.py for you in the ~/project directory.
First, locate the operators.py file in the file explorer on the left side of the VS Code editor and open it. We will write all our code in this single file.
Let's start with arithmetic operators. Add the following Python code to the operators.py file:
## Arithmetic Operators
a = 21
b = 5
print(f'{a} + {b} = {a + b}')
print(f'{a} - {b} = {a - b}')
print(f'{a} * {b} = {a * b}')
print(f'{a} / {b} = {a / b}') ## Standard division
print(f'{a} // {b} = {a // b}') ## Floor division, rounds down to the nearest whole number
print(f'{a} % {b} = {a % b}') ## Modulo, returns the remainder
print(f'{a} ** {b} = {a ** b}') ## Exponentiation, a to the power of b
After adding the code, save the file by pressing Ctrl + S.
To run the script, open the integrated terminal in VS Code by selecting Terminal > New Terminal from the top menu. Then, execute the following command:
python ~/project/operators.py
You should see the following output in the terminal:
21 + 5 = 26
21 - 5 = 16
21 * 5 = 105
21 / 5 = 4.2
21 // 5 = 4
21 % 5 = 1
21 ** 5 = 4084101
Next, let's explore comparison operators. These operators compare two values and return a Boolean value: True or False.
Add the following code to the end of your operators.py file:
## Comparison Operators
print("\n--- Comparison Operators ---")
a = 6
b = 5
print(f'{a} == {b} is {a == b}') ## Equal to
print(f'{a} != {b} is {a != b}') ## Not equal to
print(f'{a} > {b} is {a > b}') ## Greater than
print(f'{a} < {b} is {a < b}') ## Less than
print(f'{a} >= {b} is {a >= b}') ## Greater than or equal to
print(f'{a} <= {b} is {a <= b}') ## Less than or equal to
Save the file again and run it from the terminal:
python ~/project/operators.py
The output will now include the results of the comparison operations:
21 + 5 = 26
21 - 5 = 16
21 * 5 = 105
21 / 5 = 4.2
21 // 5 = 4
21 % 5 = 1
21 ** 5 = 4084101
--- Comparison Operators ---
6 == 5 is False
6 != 5 is True
6 > 5 is True
6 < 5 is False
6 >= 5 is True
6 <= 5 is False
You have now successfully used arithmetic and comparison operators in a Python script.
Practice Assignment and Logical Operators
In this step, we will practice using assignment operators and logical operators. Assignment operators are used to assign or update the value of a variable, while logical operators are used to combine conditional statements.
Continue working with the operators.py file in the VS Code editor.
First, let's add examples of assignment operators. These provide a shorthand way to perform an operation and assign the result back to the same variable.
Add the following code to the end of your operators.py file:
## Assignment Operators
print("\n--- Assignment Operators ---")
a = 10
b = 3
print(f'Initial a: {a}')
c = a
c += b ## Equivalent to c = c + b
print(f'a += b: {c}')
c = a
c -= b ## Equivalent to c = c - b
print(f'a -= b: {c}')
c = a
c *= b ## Equivalent to c = c * b
print(f'a *= b: {c}')
c = a
c /= b ## Equivalent to c = c / b
print(f'a /= b: {c}')
## Walrus operator (Python 3.8+)
## It assigns a value to a variable as part of a larger expression.
print("\n--- Walrus Operator ---")
text = 'hello python'
if (n := len(text)) > 10:
print(f'The string is long enough ({n} characters)')
Save the file and run it from the terminal:
python ~/project/operators.py
You should see the output for the assignment operators:
... (output from previous step) ...
--- Assignment Operators ---
Initial a: 10
a += b: 13
a -= b: 7
a *= b: 30
a /= b: 3.3333333333333335
--- Walrus Operator ---
The string is long enough (12 characters)
Now, let's add examples of logical operators (and, or, not). These operators work with Boolean values, but they can also work with other types. In Python, values like 0, None, and empty collections ('', [], {}) are considered False. All other values are considered True.
Add the following code to the end of your operators.py file:
## Logical Operators
print("\n--- Logical Operators ---")
x = True
y = False
print(f'{x} and {y} is {x and y}')
print(f'{x} or {y} is {x or y}')
print(f'not {x} is {not x}')
## Evaluation with non-boolean values
a = 10 ## True
b = 0 ## False
print(f'{a} and {b} returns {a and b}') ## Returns the first Falsey value or the last Truthy value
print(f'{a} or {b} returns {a or b}') ## Returns the first Truthy value or the last Falsey value
Save the file and run it again:
python ~/project/operators.py
The output will now include the results of the logical operations:
... (output from previous examples) ...
--- Logical Operators ---
True and False is False
True or False is True
not True is False
10 and 0 returns 0
10 or 0 returns 10
You have now practiced using assignment and logical operators in Python.
Learn Bitwise Operators
In this step, we will learn about bitwise operators. These operators perform operations directly on the binary (base-2) representation of integers. This is useful for low-level data manipulation.
Continue editing the operators.py file.
First, let's see the binary representation of a few numbers using the bin() function. The 0b prefix indicates that the following digits are binary.
Add this code to the end of operators.py:
## Bitwise Operators
print("\n--- Bitwise Operators ---")
a = 5 ## Binary: 0b101
b = 9 ## Binary: 0b1001
print(f'Binary of {a} is {bin(a)}')
print(f'Binary of {b} is {bin(b)}')
## For clarity, let's align them with 4 bits:
## a = 0101
## b = 1001
## Bitwise AND (&): Sets each bit to 1 if both bits are 1.
## 0101 & 1001 = 0001 (Decimal 1)
print(f'{a} & {b} = {a & b}')
## Bitwise OR (|): Sets each bit to 1 if one of the two bits is 1.
## 0101 | 1001 = 1101 (Decimal 13)
print(f'{a} | {b} = {a | b}')
## Bitwise XOR (^): Sets each bit to 1 if only one of the two bits is 1.
## 0101 ^ 1001 = 1100 (Decimal 12)
print(f'{a} ^ {b} = {a ^ b}')
## Bitwise NOT (~): Inverts all the bits.
## ~a is equivalent to -(a+1)
print(f'~{a} = {~a}')
## Left Shift (<<): Shifts bits to the left, filling with zeros.
## Equivalent to multiplying by 2**n.
## 5 << 2 means 0101 becomes 10100 (Decimal 20)
print(f'{a} << 2 = {a << 2}')
## Right Shift (>>): Shifts bits to the right, discarding bits from the right.
## Equivalent to floor division by 2**n.
## 9 >> 2 means 1001 becomes 10 (Decimal 2)
print(f'{b} >> 2 = {b >> 2}')
Save the file and run the script from the terminal:
python ~/project/operators.py
You will see the output demonstrating each bitwise operation:
... (output from previous steps) ...
--- Bitwise Operators ---
Binary of 5 is 0b101
Binary of 9 is 0b1001
5 & 9 = 1
5 | 9 = 13
5 ^ 9 = 12
~5 = -6
5 << 2 = 20
9 >> 2 = 2
You have now learned how to use bitwise operators to manipulate integers at the bit level.
Use Membership and Identity Operators
In this final step, we will cover membership operators (in, not in) and identity operators (is, is not). Membership operators test if a value is present in a sequence, while identity operators check if two variables refer to the exact same object in memory.
Continue working with the operators.py file.
First, let's add examples of membership operators. They are commonly used with sequences like lists, tuples, and strings.
Add the following code to the end of your operators.py file:
## Membership Operators
print("\n--- Membership Operators ---")
my_list = [1, 3, 5, 7]
print(f'3 in {my_list} is {3 in my_list}')
print(f'4 not in {my_list} is {4 not in my_list}')
greeting = "hello world"
print(f'"world" in "{greeting}" is {"world" in greeting}')
Save the file and run it:
python ~/project/operators.py
The output for the membership operators will be:
... (output from previous steps) ...
--- Membership Operators ---
3 in [1, 3, 5, 7] is True
4 not in [1, 3, 5, 7] is True
"world" in "hello world" is True
Now, let's explore identity operators. It's important to understand the difference between is (identity) and == (equality). == checks if the values of two objects are the same, while is checks if they are the same object (i.e., they have the same memory address).
Add the following code to your operators.py file:
## Identity Operators
print("\n--- Identity Operators ---")
## For small integers, Python often reuses the same object.
x = 256
y = 256
print(f'x is y (for 256): {x is y}') ## This is often True
## For larger integers, Python may create separate objects.
a = 257
b = 257
print(f'a is b (for 257): {a is b}') ## This is often False
## For mutable objects like lists, they are different objects even if their content is the same.
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(f'list1 == list2: {list1 == list2}') ## Checks for equal content (True)
print(f'list1 is list2: {list1 is list2}') ## Checks for same object (False)
print(f'list1 is not list2: {list1 is not list2}') ## Checks for different objects (True)
Save the file and run it one last time:
python ~/project/operators.py
The output demonstrates the difference between equality and identity:
... (output from previous examples) ...
--- Identity Operators ---
x is y (for 256): True
a is b (for 257): True
list1 == list2: True
list1 is list2: False
list1 is not list2: True
You have successfully used membership and identity operators, completing your exploration of Python's main operator types.
Summary
In this lab, you have gained hands-on experience with the various types of operators in Python. You started by exploring fundamental arithmetic and comparison operators to perform calculations and evaluate conditions. You then practiced using assignment operators for efficient variable updates and logical operators for combining conditional logic.
Furthermore, you delved into bitwise operators to understand low-level data manipulation and concluded with membership and identity operators to check for item presence and object identity. By writing and executing code for each operator type in the VS Code editor, you have built a solid foundation for using these essential tools in your future Python programming.



