SwadhyAI Notes

All Python notes

Python Operators ➕

Types of Operators

Operators are used to perform operations on variables and values. Python divides the operators into the following groups:

➕ Arithmetic Operators

OperatorNameExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
**Exponentiationx ** y
//Floor divisionx // y

🎯 Real-World Application: Modulus (%)

The modulus operator is used to find the remainder. It's super useful for checking if a number is even or odd!

python
number = 10
if number % 2 == 0:
    print("Even")
else:
    print("Odd")

🧠 Logical Operators

Logical operators are used to combine conditional statements:

python
x = 5
print(x > 3 and x < 10) # True (Both conditions are true)
print(x > 3 or x < 4)   # True (At least one condition is true)
print(not(x > 3 and x < 10)) # False (Reverse the result)

🆔 Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

python
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x is z)  # True (z is the same object as x)
print(x is y)  # False (x and y are different objects, even if they have the same content)
print(x == y)  # True (x and y are equal)

⚠️ Watch Out: "is" vs "=="

== checks if the values are equal.
is checks if they are the same object in memory.
Always use == for comparing values like strings or numbers.

🔍 Membership Operators

Membership operators are used to test if a sequence is presented in an object:

python
x = ["apple", "banana"]

print("banana" in x)      # True
print("pineapple" not in x) # True

⚙️ Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

OperatorNameDescription
&ANDSets each bit to 1 if both bits are 1
|ORSets each bit to 1 if one of two bits is 1
^XORSets each bit to 1 if only one of two bits is 1
~NOTInverts all the bits
<<Zero fill left shiftShift left by pushing zeros in from the right
>>Signed right shiftShift right by pushing copies of the leftmost bit in from the left

✨ Pro Tip: The Walrus Operator (:=)

Introduced in Python 3.8, the walrus operator allows you to assign values to variables as part of an expression.

python
# Without walrus operator
n = len(a)
if n > 10:
    print(f"List is too long ({n} elements)")

# With walrus operator
if (n := len(a)) > 10:
    print(f"List is too long ({n} elements)")