Python Programming Operators And Expressions Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    10 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of Python Programming Operators and Expressions

Python Programming Operators and Expressions

1. Arithmetic Operators

Arithmetic operators perform basic mathematical operations like addition, subtraction, multiplication, etc.

  • Addition (+): Adds two operands.
  • Subtraction (-): Subtracts second operand from the first.
  • Multiplication (*): Multiplies two operands.
  • Division (/): Divides first operand by the second and returns a floating-point result.
  • Floor Division (//): Divides first operand by the second and returns an integer.
  • Modulus (%): Returns the remainder when first operand is divided by the second.
  • Exponentiation ()**: Raises the first operand to the power of the second.

Example:

# Variables
a = 10
b = 4

# Using arithmetic operators
print(a + b)  # Output 14
print(a - b)  # Output 6
print(a * b)  # Output 40
print(a / b)  # Output 2.5
print(a // b) # Output 2
print(a % b)  # Output 2
print(a ** b) # Output 10000

2. Comparison (Relational) Operators

Comparison operators allow you to compare the values of two operands.

  • Equal to (==): Checks if operand1 is equal to operand2.
  • Not equal to (!=): Checks if operand1 is not equal to operand2.
  • Greater than (>): Checks if operand1 is greater than operand2.
  • Less than (<): Checks if operand1 is less than operand2.
  • Greater than or equal to (>=): Checks if operand1 is greater than or equal to operand2.
  • Less than or equal to (<=): Checks if operand1 is less than or equal to operand2.

Example:

# Variables
c = 20
d = 19

# Using comparison operators
print(c == d) # Output False
print(c != d) # Output True
print(c > d)  # Output True
print(c < d)  # Output False
print(c >= d) # Output True
print(c <= d) # Output False

3. Assignment Operators

Assignment operators are used to assign values to variables.

  • =: Assigns right-hand operand to the left-hand operand.
  • +=: Adds right operand to left operand and assigns the result to left operand.
  • -=: Subtracts right operand from left operand and assigns the result to left operand.
  • *=: Multiplies right operand to left operand and assigns the result to left operand.
  • /=: Divides left operand by right operand and assigns the result to left operand.
  • %=: Takes modulus using left and right operands and assigns the result to left operand.
  • //=: Performs floor division of left operand by right operand and assigns the result to left operand.
  • **=: Performs exponentiation on left and right operand and assigns the result to left operand.
  • &=: Performs bitwise AND on left and right operand and assigns the result to left operand.
  • |=: Performs bitwise OR on left and right operand and assigns the result to left operand.
  • ^=: Performs bitwise XOR on left and right operand and assigns the result to left operand.
  • >>=: Performs bitwise right shift on left and right operand and assigns the result to left operand.
  • <<=: Performs bitwise left shift on left and right operand and assigns the result to left operand.

Example:

# Variable
e = 13

# Using assignment operators
e += 10      # equivalent to e=e+10
print(e)     # Output 23

4. Logical Operators

Logical operators are used to combine conditional statements.

  • and: Returns True if both statements are true.
  • or: Returns True if one of the statements is true.
  • not: Reverse the result, returns False if the result is true.

Example:

# Boolean variables
f = True
g = False

# Using logical operators
print(f and g) # Output False
print(f or g)  # Output True
print(not g)   # Output True

5. Bitwise Operators

Bitwise operators work bit-by-bit on binary representations of integers.

  • &: Binary AND: Sets each bit to 1 if both bits are 1.
  • |: Binary OR: Sets each bit to 1 if one of two bits is 1.
  • ^: Binary XOR: Sets each bit to 1 if only one of two bits is 1.
  • ~: Binary NOT: Inverts all the bits.
  • <<: Zero fill left shift: Shift left by pushing zeros in from the right and let the leftmost bits fall off.
  • >>: Signed right shift: Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.

Example:

# Using bitwise operators
h = 8    # 1000
i = 1    # 0001

print(h & i)  # Output 0  (1000 AND 0001)
print(h | i)  # Output 9  (1000 OR 0001)
print(h ^ i)  # Output 9  (1000 XOR 0001)
print(~h)     # Output -9 (inverts bits)
print(h << i) # Output 16 (1000 shifted left by 1)
print(h >> i) # Output 4 (1000 shifted right by 1)

6. Membership Operators

Membership operators test if a sequence is presented in an object.

  • in: Returns True if a sequence with the specified value is present in the object.
  • not in: Returns True if a sequence with the specified value is not present in the object.

Example:

j = 'Hello World'
k = ['Hello', 'World', 'Python']

# Using membership operators
print('World' in j)       # Output True
print('Python' not in k)  # Output True

7. Identity Operators

Identity operators compare the memory locations of two objects.

  • is: Returns True if both variables point to the same object.
  • is not: Returns True if both variables do not point to the same object.

Example:

l = ["apple", "banana"]
m = ["apple", "banana"]
n = l

# Using identity operators
print(l is n)         # Output True, because both point to the same list object in memory
print(l is m)         # Output False, because m is a new list object in memory
print(l is not m)     # Output True

8. Expressions

Expressions in Python are the constructs made up of variables, operators, literals, and function calls. They are essential for executing computations and operations within the language.

Types of Expressions:

  • Numeric Expressions: Involves mathematical operations performed with numeric literals or variables.
  • Relational Expressions: Uses relational operators to compare values.
  • Logical Expressions: Uses logical operators to combine multiple relational or logical expressions.
  • Bitwise Expressions: Performs bitwise operations.
  • Assignment Expressions: Involves assigning values to variables.
  • Unary Expressions: Contains single operands (unary operators, e.g., not a).
  • Binary Expressions: Contains two operands (binary operators, e.g., a + b).
  • Ternary Expressions: Uses a condition followed by two expressions based on whether the condition is true or false (syntax: x if C else y).

Example:

# Numeric expression
o = 9 + 4 * 7
print(o)               # Output 37, because it evaluates as per operator precedence rule

# Relational expression
p = 5 > 3
print(p)               # Output True

# Logical expression
q = not (10 < 5) and (5 <= 10)
print(q)               # Output True

# Bitwise expression
r = 2 << 2
print(r)               # Output 8, 2 shifted left by 2 bits

# Assignment expression
s = 12
print(s)               # Output 12 

# Unary expression
t = 4
print(-t)              # Output -4

# Binary expression
u = 7   
v = 2
print(u * v)           # Output 14

# Ternary expression
w = 5
x = 3
y = w if w > x else x  
print(y)               # Output 5

Python operators and expressions provide a powerful way to perform complex manipulations and logic within your code. Mastery of these components enhances your ability to write efficient and effective programs.

Keywords:

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Python Programming Operators and Expressions

Introduction to Python Operators and Expressions

Operators in Python are used to perform operations on variables or values. Expressions combine variables, literals, and operators to produce another value.

Types of Operators in Python:

  1. Arithmetic Operators: These perform basic mathematical operations like addition, subtraction, multiplication, etc.
  2. Assignment Operators: These assign values to variables.
  3. Comparison (Relational) Operators: These compare two values and return a boolean result.
  4. Logical Operators: These are used to combine conditional statements.
  5. Bitwise Operators: These perform operations on binary (bitwise) level.
  6. Membership Operators: These test for membership in a sequence, such as strings, lists, or tuples.
  7. Identity Operators: These compare the memory addresses of two objects.
  8. Unary Operators: There is one unary operator (-) and other special operators such as +, ~, etc.

1. Arithmetic Operators

These are used to perform arithmetic operations between numeric literals or variables.

# Define some variables
a = 10
b = 4

# Addition
print("Addition: ", a + b)  # Output: 14

# Subtraction
print("Subtraction: ", a - b)  # Output: 6

# Multiplication
print("Multiplication: ", a * b)  # Output: 40

# Division
print("Division: ", a / b)  # Output: 2.5

# Floor division
print("Floor Division: ", a // b)  # Output: 2

# Modulus
print("Modulus: ", a % b)  # Output: 2

# Exponentiation
print("Exponentiation: ", a ** b)  # Output: 10000

2. Assignment Operators

These operators are used to assign values to a Python variable.

x = 10

# Simple assignment
y = x
print("Simple assignment y =", y)  # Output: 10

# Increment and assign
x += 5    # equivalent to x = x + 5
print("Increment and assign x =", x)  # Output: 15

# Subtract and assign
x -= 3    # equivalent to x = x - 3
print("Subtract and assign x =", x)  # Output: 12

# Multiply and assign
x *= 4    # equivalent to x = x * 4
print("Multiply and assign x =", x)  # Output: 48

# Divide and assign
x /= 4    # equivalent to x = x / 4
print("Divide and assign x =", x)  # Output: 12.0

# Floor divide and assign
x //= 3   # equivalent to x = x // 3
print("Floor divide and assign x =", x)  # Output: 4.0

# Modulus and assign
x %= 2    # equivalent to x = x % 2
print("Modulus and assign x =", x)  # Output: 0.0

# Exponentiate and assign
x **= 3   # equivalent to x = x ** 3
print("Exponentiate and assign x =", x)  # Output: 0.0

3. Comparison (Relational) Operators

These operators are used to compare the values of two operands.

# Define some variables
x = 10
y = 4  

# Equal to
print("Equal to:", x == y)  # Output: False

# Not equal to
print("Not equal to:", x != y)  # Output: True

# Greater than
print("Greater than:", x > y)  # Output: True

# Less than
print("Less than:", x < y)  # Output: False

# Greater than or equal to
print("Greater than or equal to:", x >= y)  # Output: True

# Less than or equal to
print("Less than or equal to:", x <= y)  # Output: False

4. Logical Operators

These operators are used to combine conditional statements.

# Define some variables
a = True  
b = False 

# AND logical operator
print("Logical AND:", a and b)  # Output: False

# OR logical operator
print("Logical OR:", a or b)  # Output: True

# NOT logical operator
print("Logical NOT:", not b)  # Output: True

5. Bitwise Operators

These operators work on bits and perform bit-by-bit operations.

# Define some variables
x = 10    # Binary: 1010 
y = 4     # Binary: 0100

# Bitwise AND
print("Bitwise AND:", x & y)  # Output: 0 (Binary: 0000)

# Bitwise OR
print("Bitwise OR:", x | y)  # Output: 14 (Binary: 1110)

# Bitwise XOR
print("Bitwise XOR:", x ^ y)  # Output: 14 (Binary: 1110)

# Bitwise NOT
print("~x:", ~x)  # Output: -11 (Binary: -(2's complement: 1011))

# Bitwise LEFT SHIFT
print("Bitwise LEFT SHIFT:", x << 1)  # Output: 20 (Binary: 10100)

# Bitwise RIGHT SHIFT
print("Bitwise RIGHT SHIFT:", x >> 2)  # Output: 2 (Binary: 10)

6. Membership Operators

These operators are used to check if a value exists (is a member) of a sequence (such as string, list, tuple, etc.).

# Define some sequences
string = "Hello"
lst = [1, 2, 3, 4, 5]
tuple = (6, 7, 8, 9)

# Check if 'e' is in string
print("'e' in string?:", 'e' in string)  # Output: True

# Check if 3 is in list
print("3 in lst?:", 3 in lst)  # Output: True

# Check if 9 is not in tuple
print("9 not in tuple?:", 9 not in tuple)  # Output: False

7. Identity Operators

These operators are used to check if two variables point to the same object or not.

# Define some variables
x = 10
y = 10
z = 20

# Identity equality
print("x is the same object as y:", x is y)  # Output: True

# Identity inequality
print("x is not the same object as z:", x is not z)  # Output: True

8. Unary Operators

These are operators that act upon a single operand to produce a result.

# Positive unary operator
x = 10
print("+x:", +x)  # Output: 10

# Negative unary operator
x = -10
print("-x:", -x)  # Output: 10

# Negation unary operator (complement)
x = 10
print("~x:", ~x)  # Output: -11 (Binary: -(2's complement: 1011))

Expressions in Python

An expression is a combination of variables, values, operators, and function calls that produce another value.

# Expression using arithmetic operators
result = (5 + 3) * (4 - 2)
print("The expression result: ", result)  # Output: 16

# Expression using comparison operators with if-else
age = 25

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

# Expression using logical operators
isLoggedIn = True
hasPermissions = False

if isLoggedIn and hasPermissions:
    print("You can access the page.")
else:
    print("Access denied.")

Conclusion

Using operators and expressions allows you to perform various computations and comparisons in your Python programs. Each type of operator serves a different purpose and understanding how they work is fundamental to writing effective code. Practice these concepts by experimenting with them in your code editor!

Top 10 Interview Questions & Answers on Python Programming Operators and Expressions

1. What are the types of operators available in Python?

Answer: Python supports a wide variety of operators which can be categorized as:

  • Arithmetic Operators: Used for basic mathematical operations like addition (+), subtraction (-), multiplication (*), division (/), floor division (//), modulus (%), and exponentiation (**).
  • Comparison (Relational) Operators: These operators compare the values of two operands (==, !=, >, <, >=, <=).
  • Assignment Operators: Assign values to variables (=, +=, -=, *=, /=, //=, %=, **=).
  • Logical Operators: Used to combine conditional statements (and, or, not).
  • Bitwise Operators: Perform operations on binary numbers (&, |, ^, ~, <<, >>).
  • Membership Operators: Check for the presence of a value in an object (in, not in).
  • Identity Operators: Check whether two objects are the same object in memory (is, is not).

2. Can you explain the difference between == and is in Python?

Answer: In Python, == checks if the values of two operands are equal, while is checks if the operands refer to the same object in memory.

a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b)  # Output: True, because values are the same
print(a is b)  # Output: False, because they are different objects
print(a is c)  # Output: True, because c and a are references to the same object

3. How do you perform exponentiation in Python?

Answer: Exponentiation in Python is performed using the ** operator. For example, 2 ** 3 returns 8, which is 2 raised to the power of 3.

4. What does the % operator do in Python?

Answer: The % operator is known as the modulus operator. It gives the remainder after a number divided by another. For example, 10 % 3 equals 1.

5. Describe how bitwise operators work with examples.

Answer: Bitwise operators work on bits. Assume x = 6 (00110) and y = 9 (01001):

  • & (AND): Returns one if both bits at the same place are 1, else 0. x & y will be (00000) or 0.
  • | (OR): Returns one if any of the two bits at the same place is 1, else 0. x | y will give (01111) or 15.
  • ^ (XOR): Returns one if only one of the two bits at the same place is 1, else 0. x ^ y will produce (01111) or 15.
  • ~ (NOT or complement): Inverts all bits. ~x will give (-7), where the sign bit is inverted.
  • << (Zero fill left shift): Shifts the bits left, and fills 0 on voids left as a result. x << 2 gives 24, binary becomes 11000.
  • >> (Signed right shift): Moves the bits to the right and shifts in 0 from the left. If it is a negative number, it fills in on the left with 1. x >> 2 will result in 1, binary becomes 00011.

6. When would you use // (floor division) instead of / (true division)?

Answer: Floor division (//) will divide the first operand by the second and then round down to the nearest whole number, whereas true division (/) will return a float that includes the decimal precision. Use // when integer output is desired or when you need to perform integer division without floating-point results.

result_floor = 9 // 2  # result_floor will be 4
result_true = 9 / 2    # result_true will be 4.5

7. Explain membership operators in Python.

Answer: Membership operators (in and not in) are used to test whether a value or variable is found within a sequence. in will be True if the sequence contains the element, and False otherwise. Similarly, not in will be True if the elements are not found in the sequence.

s = 'Hello World'
print('H' in s)         # Returns: True
print('Wor', in s)      # SyntaxError, correct usage without comma

l = [1, 2, 3, 4, 5]
print(3 in l)         # Returns: True
print(6 not in l)     # Returns: True

8. What is the purpose of the ternary conditional operator in Python?

Answer: Python provides a conditional expression also known as the ternary operator, which is used to evaluate simple conditions in a single line. It's typically written as condition_if_true if condition else condition_if_false.

a = 10
b = 20
# Finding the max value between a and b without using built-in functions
max_val = a if a > b else b # max_val will be 20

9. How do you use logical operators in Python?

Answer: Logical operators (and, or, not) are used to form compound conditions by combining simple boolean expressions. Examples:

  • and: Both conditions must be true to return true; otherwise, it returns false.
  • or: At least one of the conditions needs to be true to return true.
  • not: Inverts a boolean expression (true becomes false and vice versa).
x = 5
y = 10
print(x > 3 and y < 15)  # Output: False
print(x > 3 or y < 15)   # Output: True
print(not(x > 3))        # Output: False

10. Could you explain operator precedence and associativity in Python?

Answer: Operator precedence determines the order in which operators are evaluated within an expression. The higher precedence operator gets evaluated before a lower precedence operator. Precedence levels from highest to lowest are: parentheses, exponentiation, unary positive/negative, multiplication/division, addition/subtraction, shift, relational, equality, bit-wise AND, bit-wise XOR, bit-wise OR, logical NOT, logical AND, logical OR, conditional, assignment, and lambda.

Associativity, on the other hand, deals with operators that have the same precedence to determine the order of operations. Most operators in Python use left-to-right associativity, which means operations are grouped from the left (e.g., a + b - c is equivalent to ((a + b) - c)). Exceptions include exponentiation (**), which uses right-to-left associativity.

Example:

Consider the following code:

You May Like This Related .NET Topic

Login to post a comment.