Code Crafter IT Innovation
Loading...
  • Bansal Computer Center
  • punjabedu.bansalcenter.com

Python Operators

Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations. In Python, these operators support integers, floating-point numbers, and even complex numbers.

OperatorNameDescriptionExampleOutput
+AdditionAdds two operands together.15 + 520
-SubtractionSubtracts the right operand from the left.50 - 2030
*MultiplicationMultiplies two operands.4 * 3.514.0
/DivisionDivides the left operand by the right. Always returns a float.10 / 42.5
%ModulusReturns the remainder after division.10 % 31
**ExponentiationLeft operand raised to the power of the right.2 ** 416
//Floor DivisionDivides and rounds down to the nearest whole number.10 // 33

Special Cases in Arithmetic:

Python handles division differently than many languages. Standard division (/) always results in a decimal, while Floor Division (//) "chops off" the decimal part.

# Mixed Type Arithmetic
print(5 + 2.0)    # Result: 7.0 (Int + Float = Float)

# Negative Floor Division
print(-10 // 3)   # Result: -4 (Rounds down to the smaller integer)

# String Repetition
print("Hi! " * 3) # Result: Hi! Hi! Hi! 

Assignment Operators

Assignment operators are used to store values in variables. Compound assignment operators (like +=) are used to update the value of a variable based on its current value.

OperatorExampleSame AsDescription
=x = 10x = 10Simple assignment
+=x += 5x = x + 5Add and Assign
-=x -= 2x = x - 2Subtract and Assign
*=x *= 3x = x * 3Multiply and Assign
/=x /= 2x = x / 2Divide and Assign
%=x %= 3x = x % 3Modulus and Assign
**=x **= 2x = x ** 2Power and Assign

Why use Compound Assignment?

Compound operators make the code more concise and are generally more efficient for the Python interpreter to execute.

count = 0
count += 1  # Increments by 1
count += 1  # count is now 2

# Usage in a loop
total = 100
total *= 1.10 # Adds 10% tax/interest

Comparison (Relational) Operators

Comparison operators evaluate the relationship between two operands. The result is always a Boolean (True or False). These are the backbone of conditional logic.

OperatorNameExampleResult
==Equal to10 == 10True
!=Not Equal to10 != 5True
>Greater than20 > 15True
<Less than5 < 10True
>=Greater or equal15 >= 15True
<=Less or equal8 <= 10True

Comparing Different Data Types:

Logical Operators

Logical operators are used to combine multiple conditional statements. They are often used in if statements to check if several criteria are met.

[Image of truth tables for AND OR NOT logical operators]
OperatorLogicCondition to return True
andx and yIf BOTH x and y are True
orx or yIf AT LEAST ONE of x or y is True
notnot xReturns True if x is False (Inverts result)

Short-Circuit Evaluation:

Python is smart: in an or statement, if the first part is True, it won't even look at the second part. In an and statement, if the first part is False, it stops immediately.

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive!")

is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
    print("Office is closed.")

Membership & Identity Operators

Membership Operators

These check if a value is part of a collection (like a list, tuple, set, or string).

fruits = ["apple", "mango", "orange"]
print("mango" in fruits)      # True
print("banana" not in fruits) # True

Identity Operators

Identity operators compare the memory location of two objects. They check if two variables are the exact same instance.

a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b) # True (Values are same)
print(a is b) # False (Different objects in memory)
print(a is c) # True (Same object)

Bitwise & Unary Operators

Bitwise Operators

These operate on binary digits (bits) of integers. They are used in low-level programming, graphics, and network protocols.

SymbolNameAction
&ANDSets bit to 1 if both bits are 1
|ORSets bit to 1 if one of the bits is 1
^XORSets bit to 1 if only one of the bits is 1
~NOTInverts all bits (-(x+1))
<<Left ShiftMoves bits left, filling with zeros (Multiplies by 2)
>>Right ShiftMoves bits right (Divides by 2)

Unary Operators

A unary operator is an operator that takes only one operand. The most common is the unary minus to indicate negative numbers.

x = 10
print(-x)  # Result: -10
print(+x)  # Result: 10

# Bitwise Unary
print(~x)  # Result: -11

Precedence of Operators

Operator precedence decides the order of evaluation of operators in an expression. It ensures that expressions are evaluated properly and consistently.

The Golden Rule:

Brackets → Maths → Comparison → Logic → Assignment (B → M → C → L → A)

PriorityOperatorsDescription
1()Parentheses (Highest)
2**Exponentiation
3Unary + -Positive, Negative
4* / // %Multiplication, Division, Floor Div, Modulo
5+ -Addition, Subtraction
6<< >>Bitwise Shifts
7&Bitwise AND
8^Bitwise XOR
9|Bitwise OR
10< <= > >= == !=Comparisons
11notLogical NOT
12andLogical AND
13orLogical OR
14=Assignment (Lowest)

Associativity:

# Examples
result1 = 10 + 2 * 3        # 16 (Multiplication first)
result2 = (10 + 2) * 3      # 36 (Brackets first)
result3 = 10 > 5 and 5 > 2  # True
result4 = True or False and False  # True (and evaluated before or)

What students Say?

Here are the stdudents...

#

Contact Us

Empower your tech dreams with us. Get in touch!

  • #
  • #
  • #
  • #
  • #