Learning Python: Operators

Table of contents

Operators

Operators are the constructs, which can manipulate the value of operands. Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called the operator.

Types of Operator

Python language supports the following types of operators-

Python Arithmetic Operators

Assume variable a holds the value 10 and variable b holds the value 21, then-

Operators and their description:-

  a + b = 31
  a - b = -11
  a \* b = 210
  b / a = 2.1
  b%a=1
  a\*\*b =10 to the power 20
  9//2 = 4 and 9.0//2.0 = 4.0

Python Comparison Operators

These operators compare the values on either side of them and decide the relation among them. They are also called Relational operators.

Assume variable a holds the value 10 and variable b holds the value 20, then-

  (a == b) is not true.
  (a!= b) is true.
  (a > b) is not true.
  (a < b) is true.
  (a >= b) is not true.
  (a <= b) is true.

Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then-

  c = a + b assigns value of a + b into c
  c += a is equivalent to c = c + a
  c -= a is equivalent to c = c - a
  c \*= a is equivalent to c = c \* a
  c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a
  c %= a is equivalent to c = c % a
  c \*\*= a is equivalent to c = c \*\* a
  c //= a is equivalent to c = c // a

Python Bitwise Operators

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows-

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

Python’s built-in function bin() can be used to obtain binary representation of an integer number.

The following Bitwise operators are supported by Python language-

  (a & b) (means 0000 1100)
  (a | b) = 61 (means 0011 1101)
  (a ^ b) = 49 (means 0011 0001)
  (~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.
  a << = 240 (means 1111 0000)
  a >> = 15 (means 0000 1111)

Python Logical Operators

The following logical operators are supported by Python language. Assume variable a holds True and variable b holds False then-

  (a and b) is False.
  (a or b) is True.
  Not(a and b) is True.

Python Membership Operators (IMPORTANT)

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below-

in

Evaluates to true, if it finds a variable in the specified sequence and false otherwise.

fruits = ['apple', 'banana', 'cherry']
print('apple' in fruits)  # Output: True
print('grape' in fruits)  # Output: False
sentence = "The quick brown fox"
print("quick" in sentence)  # Output: True
print("slow" in sentence)   # Output: False
user_info = {'name': 'Alice', 'age': 25}
print('name' in user_info)  # Output: True
print('email' in user_info) # Output: False
numbers = (1, 2, 3, 4, 5)
print(3 in numbers)  # Output: True
print(6 in numbers)  # Output: False
email = "[email protected]"
if "@" in email and email.endswith(".com"):
    print("This looks like a valid email address!")
else:
    print("Invalid email format.")
def contains_keyword(text, keyword):
    return keyword in text

sentence = "Learning Python is fun!"
print(contains_keyword(sentence, "Python"))  # Output: True
print(contains_keyword(sentence, "python"))  # Output: False (case-sensitive)

not in

The not in operator is used to check if a value does not exist within a sequence, such as a list, tuple, string, or dictionary. Here are a few examples of using the not in operator:

fruits = ['apple', 'banana', 'cherry']
print('grape' not in fruits)  # Output: True
print('apple' not in fruits)  # Output: False
sentence = "The quick brown fox"
print("slow" not in sentence)  # Output: True
print("quick" not in sentence) # Output: False
user_info = {'name': 'Alice', 'age': 25}
print('email' not in user_info) # Output: True
print('name' not in user_info)  # Output: False
email = "[email protected]"
if "@" not in email or not email.endswith(".com"):
    print("Invalid email format.")
else:
    print("This looks like a valid email address!")

Python Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators as explained below:

is

The is operator check if two variables refer to the same object in memory. It does not check for equality of values but rather if both variables point to the same memory location. Here are some examples of using the is operator:

a = 5
b = 5
print(a is b)  # Output: True (because of integer caching in Python)
c = 1000
d = 1000
print(c is d)  # Output: False (because integers larger than 256 are not cached)
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 is list2)  # Output: False (because they are different objects)
str1 = "hello"
str2 = "hello"
print(str1 is str2)  # Output: True (because of string interning in Python)
my_var = None
print(my_var is None)  # Output: True
class Person:
    def __init__(self, name):
        self.name = name

person1 = Person("Alice")
person2 = Person("Alice")
print(person1 is person2)  # Output: False (because they are different instances)

is not

The is not operator in Python is used to check if two variables do not refer to the same object in memory. It is the opposite of the is operator. Here are some examples of using the is not operator:

a = 5
b = 5
print(a is not b)  # Output: False (because of integer caching in Python)
c = 1000
d = 1000
print(c is not d)  # Output: True (because integers larger than 256 are not cached)
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 is not list2)  # Output: True (because they are different objects)
str1 = "hello"
str2 = "hello".upper().lower()  # Creates a new string object
print(str1 is not str2)  # Output: True (because they are different objects)
my_var = "hello"
print(my_var is not None)  # Output: True
class Person:
    def __init__(self, name):
        self.name = name

person1 = Person("Alice")
person2 = Person("Alice")
print(person1 is not person2)  # Output: True (because they are different instances)
my_var = "hello"
if my_var is not None:
    print("Variable is not None.")
else:
    print("Variable is None.")

Python Operators Precedence

Python operators precedence defines the order in which operations are performed when multiple operators are present in an expression. This order is crucial for ensuring that expressions are evaluated correctly. Here’s an overview of Python operator precedence:

Precedence Order

Python operators are evaluated in the following order from highest to lowest precedence:

  1. Parentheses: Expressions inside parentheses are evaluated first.
  2. Exponentiation (**): Right-to-left associativity.
  3. Unary operators (+, -, ~, not): Right-to-left associativity.
  4. Multiplication and Division (*, /, //, %): Left-to-right associativity.
  5. Addition and Subtraction (+, -): Left-to-right associativity.
  6. Comparison operators (==, !=, >, <, >= , <=): Left-to-right associativity.
  7. Logical operators (not, and, or): not has the highest precedence among logical operators, followed by and, and then or.
  8. Assignment operators (=, +=, -=, etc.): Right-to-left associativity.

Examples

Example 1: Arithmetic Operations

# Multiplication has higher precedence than addition
print(10 + 5 * 3)  # Output: 25
# Equivalent to: print(10 + (5 * 3))

Example 2: Using Parentheses

# Parentheses override normal precedence
print((10 + 5) * 3)  # Output: 45
# Equivalent to: print(15 * 3)

Example 3: Logical Operations

# Logical operators are evaluated last
x = 5
y = 2
print(x * 5 >= 10 and y - 6 <= 20)
# First, perform arithmetic, then logical operations

Example 4: Associativity

# Left-to-right associativity for multiplication and division
print(10 / 2 * 3)  # Output: 15.0
# Equivalent to: print((10 / 2) * 3)

Best Practices

Conclusion

We learned about operators in Python, they’re very important to understand to properly create algorithms for the respective activities we want to do, they share a lot of similarities with Javascript overall, but what I liked the most were the in and is, they do seem very useful and we got to see some examples about how to apply them.

See you on the next post.

Sincerely,

Eng. Adrian Beria.