Python

Python Operators

Operators are special symbols or keywords used to perform operations on values and variables.

For example:

x = 10 y = 5

print(x + y)

Here:

  • x and y are operands
  • + is the operator
  • x + y is an expression

Output:

15

Python provides several categories of operators:

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Logical Operators
  5. Membership Operators
  6. Identity Operators
  7. Bitwise Operators

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations.

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33.333...
//Floor Division10 // 33
%Modulus10 % 31
**Exponentiation10 ** 31000

Addition

a = 10 b = 5

print(a + b)

Output:

15

Subtraction

print(a - b)

Output:

5

Multiplication

print(a * b)

Output:

50

Division

print(a / b)

Output:

2.0

Notice that / normally produces a float.

2. Floor Division //

Floor division returns the quotient after removing the fractional portion according to floor division rules.

print(10 // 3)

Output:

3

Compare:

print(10 / 3)
print(10 // 3)

Output:

3.3333333333333335
3

Important with negative numbers

print(-10 // 3)

Output:

-4

This is because floor division moves toward negative infinity, not simply toward zero.

3. Modulus %

The modulus operator returns the remainder after division.

print(10 % 3)

Output:

1

Because:

10 ÷ 3 = 3 remainder 1

A very useful example is checking whether a number is even or odd:

number = 12

print(number % 2)

Output:

0

If:

number = 13

print(number % 2)

Output:

1

We will use this heavily when learning conditions.

4. Exponentiation **

The exponentiation operator raises one number to the power of another.

print(2 ** 3)

Output:

8

Because:

2 × 2 × 2 = 8

More examples:

print(5 ** 2)
print(10 ** 3)
print(16 ** 0)

Output:

25
1000
1

5. Assignment Operators

Assignment operators are used to assign or update values.

The basic assignment operator is:

=

Example:

x = 10

Python also provides compound assignment operators.

OperatorExampleEquivalent
=x = 5Assign
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
//=x //= 5x = x // 5
%=x %= 5x = x % 5
**=x **= 5x = x ** 5

Example

score = 50

score += 10

print(score)

Output:

60

This:

score += 10

means:

score = score + 10

6. Comparison Operators

Comparison operators compare two values.

The result is always:

True

or:

False
OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Example:

a = 10 b = 5

print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)

Output:

False
True
True
False
True
False

7. = vs ==

This is one of the most important concepts for beginners.

=

Used for assignment:

age = 25

Meaning:

Store 25 in age.

==

Used for comparison:

age == 25

Meaning:

Is the value of age equal to 25?

Example:

age = 25

print(age == 25)

Output:

True

8. Comparing Strings

Comparison operators can also be used with strings.

name = "Raj"

print(name == "Raj")
print(name == "John")

Output:

True
False

Python is case-sensitive:

print("Python" == "python")

Output:

False

9. Comparing Strings Alphabetically

Python can compare strings using comparison operators.

print("apple" < "banana")

Output:

True

String comparison is based on Unicode character ordering.

For beginner programs, this can be useful for simple alphabetical comparisons.

10. Logical Operators

Logical operators combine or modify conditions.

Python has three main logical operators:

and
or
not

and

and returns True when both conditions are true.

age = 25

print(age > 18 and age < 30)

Both conditions are true:

True

Example:

username = "admin" password = "1234"

print(username == "admin" and password == "1234")

Output:

True

11. or

or returns True if at least one condition is true.

age = 25

print(age < 18 or age > 20)

The second condition is true:

True

Example:

day = "Saturday"

print(day == "Saturday" or day == "Sunday")

Output:

True

12. not

not reverses a Boolean result.

x = True

print(not x)

Output:

False

Another example:

age = 25

print(not age < 18)

Since:

age < 18

is False, not makes it:

True

13. Truth Table for Logical Operators

and

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

or

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

not

Anot A
TrueFalse
FalseTrue

14. Membership Operators

Membership operators check whether a value exists inside a collection.

Python provides:

in
not in

Example:

fruits = ["apple", "mango", "banana"]

print("mango" in fruits)

Output:

True

And:

print("orange" in fruits)

Output:

False

15. not in

fruits = ["apple", "mango", "banana"]

print("orange" not in fruits)

Output:

True

Membership operators are especially useful with:

  • Lists
  • Tuples
  • Sets
  • Strings
  • Dictionaries

16. Membership with Strings

text = "Python Bootcamp"

print("Python" in text)
print("Java" in text)

Output:

True
False

You can also check individual characters:

print("P" in "Python")

Output:

True

17. Membership with Dictionaries

For dictionaries, in checks the keys by default.

student = {
    "name": "Raj",
    "age": 25,
    "city": "Kathmandu"
}

print("name" in student)
print("Raj" in student)

Output:

True
False

To check values:

print("Raj" in student.values())

Output:

True

18. Identity Operators

Identity operators check whether two variables refer to the same object.

Python provides:

is
is not

Example:

x = None

print(x is None)

Output:

True

A common use is checking for None.

result = None

if result is None:
    print("No result available")

19. is vs ==

This is an important distinction.

==

Checks whether two values are equal.

is

Checks whether two references point to the same object.

Example:

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

print(a == b)
print(a is b)

Output:

True
False

Why?

The lists contain the same values, so:

a == b

is True.

But they are two separate list objects, so:

a is b

is False.

20. is not

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

print(a is not b)

Output:

True

Again, the two lists have equal contents but are separate objects.

21. Bitwise Operators

Bitwise operators work at the level of binary bits.

They are mainly used in:

  • Low-level programming
  • Embedded systems
  • Networking
  • Permissions/flags
  • Performance-sensitive operations
  • Certain algorithms

Python provides:

OperatorName
&AND
``
^XOR
~NOT
<<Left Shift
>>Right Shift

22. Bitwise AND &

Consider:

6 = 110
3 = 011

Bitwise AND:

110
011
---
010

Therefore:

print(6 & 3)

Output:

2

23. Bitwise OR |

print(6 | 3)

Output:

7

Because:

110
011
---
111

111 in binary is 7.

24. Bitwise XOR ^

XOR returns 1 when the two corresponding bits are different.

print(6 ^ 3)

Output:

5

Because:

110
011
---
101

101 is 5.

25. Bitwise NOT ~

The ~ operator inverts bits.

x = 5

print(~x)

Output:

-6

This can initially seem surprising.

Python represents integers using a signed integer model, so:

~x = -(x + 1)

Therefore:

~5 = -6

26. Left Shift <<

Left shift moves bits toward the left.

print(5 << 1)

Output:

10

Conceptually:

5  = 0101
     ↓ shift left
10 = 1010

A left shift by one position is equivalent to multiplying by 2 for these integer cases.

27. Right Shift >>

Right shift moves bits toward the right.

print(10 >> 1)

Output:

5

Conceptually:

10 = 1010
      ↓ shift right
5  = 0101

28. Operator Precedence

When an expression contains multiple operators, Python follows an order of evaluation.

For example:

result = 10 + 5 * 2

print(result)

Output:

20

It does not calculate:

(10 + 5) × 2 = 30

Instead, multiplication happens first:

10 + (5 × 2)
10 + 10
20

29. Common Precedence Order

A simplified order to remember:

()
**
+x, -x
*, /, //, %
+, -
<, <=, >, >=
==, !=
not
and
or

For beginners, the most important rule is:

Use parentheses when you want your intention to be obvious.

Example:

result = (10 + 5) * 2

print(result)

Output:

30

30. Parentheses Make Expressions Clear

Instead of:

total = price * quantity + tax

you can write:

total = (price * quantity) + tax

The second version makes the intended calculation easier to understand.

31. Operator Example : Shopping

price = 1500 quantity = 3 discount = 10

subtotal = price * quantity discount_amount = subtotal * discount / 100 final_price = subtotal - discount_amount

print("Subtotal:", subtotal)
print("Discount:", discount_amount)
print("Final Price:", final_price)

Output:

Subtotal: 4500
Discount: 450.0
Final Price: 4050.0

This combines:

  • Multiplication
  • Division
  • Subtraction
  • Assignment

32. Operator Example : Even or Odd

The modulus operator is perfect for this.

number = 17

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

Output:

Odd

This introduces an important pattern:

remainder + comparison

We will use this heavily in conditional statements.

33. Operator Example : Eligibility

age = 22 has_id = True

print(age >= 18 and has_id)

Output:

True

This combines:

  • Comparison operator >=
  • Logical operator and

34. Operator Example : Searching

skills = ["Python", "Django", "SQL"]

skill = "Python"

print(skill in skills)

Output:

True

This uses the membership operator in.

35. Copy Code

# ========================================== # Python Operators # ==========================================

# Arithmetic Operators

a = 10 b = 3

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)


# Assignment Operators

x = 10

x += 5 print("After += :", x)

x -= 3 print("After -= :", x)

x *= 2 print("After *= :", x)

x /= 2 print("After /= :", x)

x //= 2 print("After //= :", x)

x %= 3 print("After %= :", x)

x **= 2 print("After **= :", x)


# Comparison Operators

a = 10 b = 5

print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)


# Logical Operators

age = 25

print(age > 18 and age < 30)
print(age < 18 or age > 20)
print(not age < 18)


# Membership Operators

fruits = ["apple", "mango", "banana"]

print("mango" in fruits)
print("orange" in fruits)
print("orange" not in fruits)


# Membership with strings

text = "Python Bootcamp"

print("Python" in text)
print("Java" not in text)


# Identity Operators

result = None

print(result is None)
print(result is not None)


# Comparing equality vs identity

list1 = [1, 2, 3]
list2 = [1, 2, 3]

print(list1 == list2)
print(list1 is list2)


# Bitwise Operators

x = 6 y = 3

print("AND:", x & y)
print("OR:", x | y)
print("XOR:", x ^ y)
print("NOT:", ~x)
print("Left Shift:", x << 1)
print("Right Shift:", x >> 1)


# Operator precedence

result = 10 + 5 * 2

print(result)

result = (10 + 5) * 2

print(result)

36. Practice Exercise 1 : Basic Calculator

Create a program that asks the user for two numbers and displays:

  • Addition
  • Subtraction
  • Multiplication
  • Division
  • Floor division
  • Remainder
  • Power

Example:

Enter first number: 10
Enter second number: 3

Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.333...
Floor Division: 3
Remainder: 1
Power: 1000

37. Practice Exercise 2 : Even or Odd

Ask the user to enter a number.

Use % to determine whether it is:

Even

or:

Odd

38. Practice Exercise 3 : Age Eligibility

Ask the user for their age.

Check whether:

age >= 18

Print:

Eligible

or:

Not Eligible

39. Practice Exercise 4 : Login Check

Create:

username = "admin" password = "python123"

Ask the user to enter their username and password.

Use:

==
and

to determine whether the login details are correct.

40. Practice Exercise 5 : Course Search

Create:

courses = [
    "Python",
    "Django",
    "MERN",
    "Data Science",
    "Machine Learning"
]

Ask the user to enter a course name.

Use in to check whether the course exists.

41. Practice Exercise 6 : Shopping Discount

Ask the user for:

  • Product price
  • Quantity
  • Discount percentage

Calculate:

subtotal
discount amount
final price

Use arithmetic operators.

42. Challenge : Student Result System

Create a program that asks for marks in three subjects.

Calculate:

Total
Average

Then use comparison and logical operators to determine whether the student passed.

For example:

Each subject must be >= 40

and:

Average must be >= 50

The student passes only when both conditions are satisfied.

43. Operator Quick Reference

CategoryOperators
Arithmetic+ - * / // % **
Assignment= += -= *= /= //= %= **=
Comparison== != > < >= <=
Logicaland or not
Membershipin not in
Identityis is not
Bitwise& | ^ ~ << >>
Interactive Sandbox
Python