😢Operators

Python operators are the symbols that allow us to perform different types of operations on variables and values. They are the building blocks of any programming language, and Python is no exception. Python provides a wide range of operators that can be used to perform arithmetic, logical, comparison, assignment, and bitwise operations.

Understanding the different types of operators is crucial to writing efficient and error-free code in Python. In this section, we will explore the different types of operators available in Python and learn how to use them effectively in our programs. So buckle up and get ready to dive into the world of Python operators!

I. Arithmetic Operators

Arithmetic operators are used in Python to perform basic arithmetic operations such as addition, subtraction, multiplication, division, and more. These operators are used on numeric data types such as integers, floats, and complex numbers.

Python provides the following arithmetic operators:

Operator
Name
Example
Result

+

Addition

2 + 3

5

-

Subtraction

5 - 2

3

*

Multiplication

3 * 4

12

/

Division

10 / 2

5

%

Modulus

10 % 3

1

**

Exponentiation

2 ** 3

8

//

Floor Division

10 // 3

3

The floor division (//) operator returns the largest integer that is less than or equal to the division result.

a. Addition

Addition is one of the most basic arithmetic operations in Python. It is denoted by the + symbol and is used to add two numbers or concatenate two strings. For example, if we want to add two numbers x and y together, we can use the + operator like this:

x = 5
y = 3
sum = x + y
print(sum)  # Output: 8

Similarly, if we want to concatenate two strings a and b, we can use the + operator like this:

a = "Hello"
b = "World"
concatenation = a + " " + b
print(concatenation)  # Output: Hello World

In both cases, the + operator performs the desired operation and returns a new value that we can assign to a variable or use directly.

b. Subtraction

The subtraction operator (-) is used to subtract one value from another. It takes two operands and returns the difference between them. For example, 5 - 3 will return 2, and 10.5 - 3.2 will return 7.3.

In Python, the subtraction operator can also be used with variables. For example:

a = 5
b = 3
c = a - b
print(c)  # Output: 2

Note that the subtraction operator can also be used with negative numbers. For example, 5 - (-3) will return 8.

c. Multiplication

Multiplication is a mathematical operation that is represented by the symbol * in Python. It is used to find the product of two or more values. Here's an example:

a = 10
b = 5
c = a * b
print(c)  # Output: 50

In the above example, we have two variables a and b with values 10 and 5 respectively. We multiply these two variables using the * operator and store the result in the variable c. Finally, we print the value of c which is 50 (the product of a and b).

d. Division

In Python, the / operator is used for division. It returns the quotient (result of division) in the form of a float, even if both the operands are integers. If you want to get the quotient as an integer, you can use the // operator, which performs floor division.

Here's an example:

a = 10
b = 3

# Floating point division
c = a / b
print(c) # Output: 3.3333333333333335

# Integer division
d = a // b
print(d) # Output: 3

In the example above, we divide a by b using both the / and // operators. The result of the floating point division is stored in c, which is a float, while the result of the integer division is stored in d, which is an integer.

d. Modulus

Modulus operator returns the remainder of the division operation between two operands. It is represented by the percentage sign %.

For example, the expression 9 % 4 returns 1 because when 9 is divided by 4, the remainder is 1.

Here is an example code snippet:

a = 9
b = 4
result = a % b
print(result)

Output:

1

e. Exponentiation

Exponentiation is another arithmetic operator in Python represented by the double asterisk symbol (**). It raises the first operand to the power of the second operand.

Syntax:

base ** exponent

Here, the base is the first operand, and the exponent is the second operand.

Example:

2 ** 3  # Output: 8

In the above example, 2 is raised to the power of 3, which results in 8.

f. Floor Division

Floor Division operator in Python is represented by two forward slashes // and it returns the quotient of the division operation rounding down to the nearest integer. For example, the floor division of 7 // 3 would be 2 since 3 goes into 7 two whole times with 1 left over.

Here's an example of using floor division operator:

a = 10
b = 3
result = a // b
print(result) # output: 3

In the above example, we have defined two variables a and b, and then used floor division operator // to divide a by b. Since a is 10 and b is 3, the result of a // b is 3.

II. Comparison Operators

Comparison operators, also known as relational operators, are used to compare two values or operands. In Python, comparison operators always return a boolean value - either True or False.

There are six comparison operators in Python:

  1. Equal to (==)

  2. Not equal to (!=)

  3. Greater than (>)

  4. Less than (<)

  5. Greater than or equal to (>=)

  6. Less than or equal to (<=)

These operators are used in conditional statements and loops to test whether a certain condition is true or false.

a. Equal to (==)

The equal to operator (==) is a comparison operator used to compare the equality of two operands. It returns True if the values of the two operands are equal, otherwise, it returns False.

Here's an example:

x = 5
y = 10
z = 5

print(x == y)   # False
print(x == z)   # True

In this example, the first comparison returns False because x is not equal to y. The second comparison returns True because x is equal to z.

b. Not equal to (!=)

In Python, the "not equal to" operator is represented by the exclamation mark followed by an equal sign (!=). It is a binary operator and is used to compare two values. The operator returns True if the values are not equal and False if they are equal.

Here's an example of using the "not equal to" operator in Python:

x = 10
y = 5
if x != y:
    print("x is not equal to y")
else:
    print("x is equal to y")

Output:

vbnetCopy codex is not equal to y

c. Greater than (>)

The greater than operator (>) is used to check if the left operand is greater than the right operand. It returns True if the left operand is greater than the right operand, otherwise, it returns False. Here is an example:

x = 5
y = 3
print(x > y)  # Output: True

In the example above, x is greater than y, so the expression x > y returns True.

d. Less than (<)

In Python, the less than operator < is used to compare two operands. It returns True if the left operand is less than the right operand, and False otherwise.

Here's an example:

x = 5
y = 10

if x < y:
    print("x is less than y")
else:
    print("x is not less than y")

Output:

x is less than y

In this example, x is less than y, so the if statement evaluates to True, and the first print statement is executed.

e. Greater than or equal to (>=)

The greater than or equal to operator (>=) is used to compare two values. It returns True if the left operand is greater than or equal to the right operand, and False otherwise.

For example:

honx = 5
y = 3

print(x >= y)   # Output: True
print(y >= x)   # Output: False

In this example, the first print statement returns True because x (which is 5) is greater than or equal to y (which is 3). The second print statement returns False because y is less than x.

f. Less than or equal to (<=)

The "Less than or equal to" operator is represented by the symbol "<=". It is used to check if one value is less than or equal to another value.

For example, in the expression "5 <= 10", the operator "<=" checks if 5 is less than or equal to 10. Since this is true, the expression evaluates to True. However, in the expression "10 <= 5", the operator "<=" checks if 10 is less than or equal to 5. Since this is false, the expression evaluates to False.

Here's an example code snippet demonstrating the use of the "<=" operator:

x = 5
y = 10

if x <= y:
    print("x is less than or equal to y")
else:
    print("x is greater than y")

This code will output "x is less than or equal to y", since 5 is indeed less than or equal to 10.

III. Logical Operators

Python Logical Operators are used to combine two or more conditions and perform logical operations on them. The following are the three logical operators in Python:

  1. and

  2. or

  3. not

These operators are used to perform logical operations on the operands and return a Boolean value.

  • The 'and' operator returns True if both operands are True, otherwise, it returns False.

  • The 'or' operator returns True if either of the operands is True, otherwise, it returns False.

  • The 'not' operator returns the opposite of the operand.

Let's look at depth with some examples to understand how these operators work.

a. AND

The and operator returns True if both operands are true and returns False if either one of the operands is false.

Here's the truth table for the and operator:

Operand 1
Operand 2
Result

True

True

True

True

False

False

False

True

False

False

False

False

Here's an example code snippet:

x = 5
y = 10
z = 15

if x < y and x < z:
    print("x is the smallest number")

In this example, the and operator is used to check if x is smaller than both y and z. If this condition is true, then the statement "x is the smallest number" is printed.

b. OR

The OR operator in Python is represented by or. It is a logical operator that returns True if at least one of the operands is True, and False otherwise. Here are the possible truth tables for the OR operator:

Operand 1
Operand 2
Result

False

False

False

False

True

True

True

False

True

True

True

True

Here's an example of using the OR operator in Python:

x = 5
y = 10
z = 15

if x > y or x > z:
    print("x is greater than y or z")
else:
    print("x is not greater than y or z")

In this example, x is not greater than y or z, so the output will be x is not greater than y or z.

c. NOT

The NOT operator is a unary operator that negates the value of its operand. In Python, the NOT operator is represented by the keyword "not".

The NOT operator returns True if its operand is False, and vice versa. Here's an example:

x = True
print(not x)  # Output: False

In this example, the value of x is True. However, the NOT operator negates the value of x and returns False.

IV. Assignment Operators

Have you ever wanted to quickly assign or modify a value in Python without writing a lot of code? That's where assignment operators come in handy! They allow you to perform an operation on a variable and assign the result back to the same variable in a single step. In this section, we will explore the different types of assignment operators in Python.

a. Simple Assignment Operator

The simple assignment operator in Python is denoted by the equal sign "=" and is used to assign a value to a variable. The syntax for simple assignment is:

variable = value

where variable is the name of the variable and value is the value to be assigned to the variable.

For example, the following code assigns the value 10 to the variable x:

x = 10

After executing this code, the variable x will have the value 10.

b. Arithmetic Assignment Operators

Arithmetic assignment operators are a shorthand way of performing arithmetic operations and assignment at the same time. These operators include:

  • += : adds the value of the right operand to the value of the left operand and assigns the result to the left operand.

  • -= : subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.

  • *= : multiplies the value of the left operand by the value of the right operand and assigns the result to the left operand.

  • /= : divides the value of the left operand by the value of the right operand and assigns the result to the left operand.

  • %= : computes the modulus of the value of the left operand and the value of the right operand, and assigns the result to the left operand.

  • //= : performs floor division on the value of the left operand and the value of the right operand, and assigns the result to the left operand.

  • **= : raises the value of the left operand to the power of the value of the right operand, and assigns the result to the left operand.

These operators can be used with numeric values and variables of numeric types, such as integers and floating-point numbers.

Example:

x = 10
x += 5  # equivalent to x = x + 5
print(x) # Output: 15

y = 7
y *= 3  # equivalent to y = y * 3
print(y) # Output: 21

z = 8
z //= 3 # equivalent to z = z // 3
print(z) # Output: 2

In each of the above examples, the arithmetic operation and the assignment operation are performed at the same time using the shorthand arithmetic assignment operator.

c. Bitwise Assignment Operators

Bitwise assignment operators are used to perform a bitwise operation on a variable and then assign the result to the same variable. The bitwise assignment operators include:

  • &=: Performs a bitwise AND operation on the variable and the value on the right, then assigns the result to the variable.

  • |=: Performs a bitwise OR operation on the variable and the value on the right, then assigns the result to the variable.

  • ^=: Performs a bitwise XOR operation on the variable and the value on the right, then assigns the result to the variable.

  • <<=: Performs a left shift operation on the variable by the number of bits specified on the right, then assigns the result to the variable.

  • >>=: Performs a right shift operation on the variable by the number of bits specified on the right, then assigns the result to the variable.

d. Logical Assignment Operators

There are no specific "Logical Assignment Operators" in Python, as the logical operators and, or, and not are already used for combining and negating boolean expressions. However, it is possible to use logical operators in combination with assignment operators to create compound expressions, such as x += y or z, which assigns the value of y to x if y is truthy, or the value of z otherwise.

e. Comparison Assignment Operators

There is no such thing as "Comparison Assignment Operators". The term "comparison operator" refers to operators that compare two values and return a boolean value (True or False), while "assignment operator" refers to operators that assign a value to a variable.

However, there are shorthand ways to perform a comparison and assign the result to a variable in a single line of code. For example:

  • x = 10 if a > b else 20: This assigns the value 10 to x if a > b is True, otherwise it assigns the value 20.

  • x += 1 if a == b else 2: This adds 1 to x if a == b is True, otherwise it adds 2.

  • x *= 2 if a < b else 3: This multiplies x by 2 if a < b is True, otherwise it multiplies it by 3.

V. Bitwise Operators

Bitwise operators are used to manipulate the individual bits of binary numbers. In Python, bitwise operators can be applied to integers. The bitwise operators take two operands and operate on them bit by bit to produce a result. There are six bitwise operators in Python: AND, OR, XOR, NOT, left shift, and right shift. These operators are commonly used in low-level programming, such as device driver development and network packet processing.

a. Bitwise AND

The bitwise AND operator is represented by the & symbol in Python. It performs a logical AND operation on each corresponding bit of its operands. If both bits are 1, the resulting bit is 1. Otherwise, the resulting bit is 0.

For example:

a = 10    # binary representation: 1010
b = 6     # binary representation: 0110
c = a & b # binary representation: 0010 (decimal value: 2)

In this example, a and b are two integers represented in binary. The & operator is used to perform a bitwise AND operation on the two numbers, resulting in the binary number 0010, which is equivalent to the decimal number 2. The resulting value is assigned to the variable c.

b. Bitwise OR

Bitwise OR is another binary operator that operates on two integers and performs a bitwise OR operation on their binary representations. The resulting binary representation is converted back to an integer.

The syntax for the bitwise OR operator is the pipe symbol |. For example, a | b performs a bitwise OR operation on a and b.

Here's an example:

a = 60        # binary representation: 0011 1100
b = 13        # binary representation: 0000 1101
c = a | b     # binary representation: 0011 1101
print(c)      # output: 61

In the above example, the binary OR operation on a and b results in 0011 1101, which is equal to 61 in decimal representation.

c. Bitwise XOR

Bitwise XOR (exclusive OR) operator is represented by the symbol ^ in Python. The operator returns a binary number that has a 1 in each bit position where the corresponding bits of either but not both operands are 1.

For example, let's say we have two variables a = 13 and b = 17. The binary representation of 13 is 1101 and the binary representation of 17 is 10001. Now, let's perform the bitwise XOR operation on these two variables:

a = 13         # binary representation: 1101
b = 17         # binary representation: 10001
c = a ^ b      # binary representation: 11000

In the above example, the resulting binary number is 11000, which is equivalent to the decimal number 24. Therefore, the value of the variable c will be 24.

Here is another example that demonstrates the use of bitwise XOR:

a = 0b1010     # decimal representation: 10
b = 0b1100     # decimal representation: 12
c = a ^ b      # decimal representation: 6

In this example, we first define a and b as binary numbers using the 0b prefix. We then perform the bitwise XOR operation on these two numbers and store the result in c. The resulting binary number is 0b110, which is equivalent to the decimal number 6. Therefore, the value of the variable c will be 6.

d. Bitwise NOT

Bitwise NOT is a unary operator in Python that flips the bits of a number. It is represented by the tilde (~) symbol. When applied to a binary number, the Bitwise NOT operator returns the complement of the number.

For example:

x = 7  # Binary: 0000 0111
y = ~x  # Binary: 1111 1000
print(bin(y))  # Output: -0b1000 (in two's complement form)

In the above code, the value of x is 7, which is represented in binary as 0000 0111. When we apply the Bitwise NOT operator (~) to x, it flips all the bits of the number, resulting in 1111 1000. The output is in two's complement form, which is the way negative numbers are represented in binary.

VI. Membership Operators

Membership operators are used to test if a sequence is present in an object. In Python, we have two membership operators:

  • in: Evaluates to True if the sequence is present in the object.

  • not in: Evaluates to True if the sequence is not present in the object.

These operators are typically used with strings, lists, tuples, and sets to check if a certain element or a sequence of elements is present in them.

For example:

fruits = ['apple', 'banana', 'orange']
if 'apple' in fruits:
    print('Yes, apple is in the list')
else:
    print('No, apple is not in the list')

if 'watermelon' not in fruits:
    print('Yes, watermelon is not in the list')
else:
    print('No, watermelon is in the list')

Output:

Yes, apple is in the list
Yes, watermelon is not in the list

VII. Identity Operators

Identity Operators are used to compare the memory locations of two objects. There are two identity operators in Python:

  1. is - Returns True if both variables are the same object.

  2. is not - Returns True if both variables are not the same object.

For example:

x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x is z)   # True because x and z are the same object
print(x is y)   # False because x and y are not the same object
print(x == y)   # True because the values of x and y are the same
print(x is not z)   # False because x and z are the same object
print(x is not y)   # True because x and y are not the same object

In this example, x and y have the same values, but they are not the same object. z is assigned the same memory location as x, so x and z are the same object. The is operator returns True when comparing x and z, but False when comparing x and y. The is not operator returns False when comparing x and z, but True when comparing x and y.

Last updated