PyForge ยท Python practice library
All topics

Topic 02 of 17

Operators

Arithmetic, comparison, logical, bitwise, and assignment operators.

Arithmetic
Comparison
Logical
Bitwise
Membership
Identity

Basic

2 programs

Program 1

Arithmetic operators

Basic

Perform basic math operations.

python
a, b = 17, 5
print("Sum:", a + b)
print("Diff:", a - b)
print("Product:", a * b)
print("Quotient:", a / b)
print("Floor div:", a // b)
print("Modulo:", a % b)
print("Power:", a ** b)

Program 2

Comparison & logical

Basic

Combine comparisons with and / or / not.

python
x = 15
print(x > 10 and x < 20)
print(x == 15 or x == 20)
print(not (x < 5))

Intermediate

1 program

Program 1

Bitwise operators

Intermediate

Operate at the bit level.

python
a, b = 12, 10  # 1100 & 1010
print("AND:", a & b)
print("OR :", a | b)
print("XOR:", a ^ b)
print("NOT:", ~a)
print("<<2:", a << 2)
print(">>1:", a >> 1)

Advanced

1 program

Program 1

Check power of two

Advanced

A classic bit trick using AND.

python
def is_power_of_two(n: int) -> bool:
    return n > 0 and (n & (n - 1)) == 0

for n in [1, 2, 6, 16, 18, 64]:
    print(n, is_power_of_two(n))