Python Operators

Python Operators Tutorial

Operators in Python are symbols used to perform operations on variables and values. Python supports various types of operators, including arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators.


1. Arithmetic Operators (Perform mathematical operations)

Example

a, b = 10, 3
print(a + b)  # Output: 13
print(a // b)  # Output: 3 (Floor division)
print(a ** b)  # Output: 1000 (Exponentiation)

2. Comparison Operators (Compare values and return True or False)

Example

x, y = 8, 12
print(x > y)  # Output: False
print(x != y)  # Output: True

3. Logical Operators (Used for logical conditions)

Example

x, y = 10, 5
print((x > 5) and (y < 10))  # Output: True
print(not(x > y))  # Output: False

4. Assignment Operators (Assign values to variables)

Example

x = 5
x += 2  # Equivalent to x = x + 2
print(x)  # Output: 7

5. Bitwise Operators (Perform bitwise operations on binary numbers)

Example

a, b = 5, 3
print(a & b)  # Output: 1
print(a | b)  # Output: 7
print(a ^ b)  # Output: 6
print(a << 1) # Output: 10
print(a >> 1) # Output: 2

6. Identity Operators (Check if two objects refer to the same memory location)

Example

x = [1, 2, 3]
y = x
z = [1, 2, 3]

print(x is y)  # Output: True (Same memory reference)
print(x is z)  # Output: False (Different memory reference)
print(x == z)  # Output: True (Values are the same)

7. Membership Operators (Check if a value exists in a sequence)

Example

fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)  # Output: True
print("grape" not in fruits)  # Output: True

8. Operator Precedence (Order of execution of operators)

Order of precedence (Highest to Lowest):

  1. () → Parentheses
  2. ** → Exponentiation
  3. *, /, //, % → Multiplication, Division, Floor Division, Modulus
  4. +, - → Addition, Subtraction
  5. >, <, ==, !=, >=, <= → Comparison
  6. not → Logical NOT
  7. and → Logical AND
  8. or → Logical OR

Example

result = 10 + 5 * 2  # Multiplication happens first
print(result)  # Output: 20

result = (10 + 5) * 2  # Parentheses change precedence
print(result)  # Output: 30

Conclusion

  • Operators are essential for performing operations on variables.
  • Python provides various types of operators like arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators.
  • Understanding operator precedence helps avoid unexpected results in calculations.

🚀 Master these operators, and you'll write more efficient Python programs!

Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment