# Python operators: A step-by-step guide

Python is a very popular programming language used by big companies like Google, Facebook, Instagram, Spotify, and others. It’s not only for simple tasks but can also handle complex applications and projects.

In this tutorial, we’ll learn about an important concept in Python called Operators. These operators allow us to do different things with our data. Python has different types of operators:

1. Arithmetic Operators: +, -, *, /, %, **, //
2. Assignment Operators: =, +=, -=, *=, /=, %=, //=, **=
3. Comparison Operators: ==, !=, >, <, >=, <=
4. Logical Operators: and, or, not
5. Bitwise Operators: &, |, ^, ~, <<, >>
6. Identity Operators: is, is not
7. Membership Operators: in, not in

## Arithmetic operators in Python

Arithmetic operators in Python are used for performing mathematical calculations.

2. Subtraction (-): Subtracts the second number from the first number.
3. Multiplication (*): Multiplies two numbers.
4. Division (/): Divides the first number by the second number. The result is a floating-point number.
5. Modulus (%): Returns the remainder of the division between the first number and the second number.
6. Exponentiation (**): Raises the first number to the power of the second number.
7. Floor Division (//): Divides the first number by the second number and returns the largest whole number that is less than or equal to the result.

### Example of Arithmetic operators in Python

``````# Arithmetic operators example

num1 = 10
num2 = 5
sum = num1 + num2
print("Sum:", sum)

# Subtraction
difference = num1 - num2
print("Difference:", difference)

# Multiplication
product = num1 * num2
print("Product:", product)

# Division
division = num1 / num2
print("Division:", division)

# Modulus
remainder = num1 % num2
print("Remainder:", remainder)

# Exponentiation
power = num1 ** num2
print("Power:", power)

# Floor Division
floor_division = num1 // num2
print("Floor Division:", floor_division)
``````

Output:

In this example, we perform various arithmetic operations using two numbers (num1 and num2). We calculate the sum, difference, product, division, remainder, power, and floor division between the two numbers using the respective arithmetic operators. Finally, we print the results:

``````Sum: 15
Difference: 5
Product: 50
Division: 2.0
Remainder: 0
Power: 100000
Floor Division: 2
``````

## Assignment Operators in Python

In Python, assignment operators are used to assign values to variables. These operators allow you to perform specific operations and store the result back into the variable.

1. = (Equal to): Assigns the value on the right side to the variable on the left side.
2. += (Add and assign): Adds the value on the right side to the current value of the variable, and assigns the result back to the variable.
3. -= (Subtract and assign): Subtracts the value on the right side from the current value of the variable, and assigns the result back to the variable.
4. *= (Multiply and assign): Multiplies the value on the right side with the current value of the variable, and assigns the result back to the variable.
5. /= (Divide and assign): Divides the current value of the variable by the value on the right side, and assigns the result back to the variable.
6. %= (Modulus and assign): Performs modulus operation on the variable with the value on the right side, and assigns the remainder back to the variable.
7. //= (Floor division and assign): Performs floor division on the variable with the value on the right side, and assigns the integer quotient back to the variable.
8. **= (Exponentiation and assign): Raises the variable to the power of the value on the right side, and assigns the result back to the variable.

### Example of Assignment Operators in Python

``````# Assignment operators example
x = 10
print("Initial value of x:", x)

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

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

x *= 2
print("After multiplying by 2, x =", x)

x /= 4
print("After dividing by 4, x =", x)

x %= 2
print("After taking modulus by 2, x =", x)

x //= 3
print("After floor dividing by 3, x =", x)

x **= 4
print("After exponentiation by 4, x =", x)
``````

Output:

In this example, we start with an initial value of x as 10. We then use different assignment operators (+=, -=, *=, /=, %=, //=, **=) to perform specific operations and update the value of x accordingly. The output shows the updated value of x after each operation.

``````Initial value of x: 10
After adding 5, x = 15
After subtracting 3, x = 12
After multiplying by 2, x = 24
After dividing by 4, x = 6.0
After taking modulus by 2, x = 0.0
After floor dividing by 3, x = 0.0
After exponentiation by 4, x = 0.0
``````

## Comparison Operators in Python

Comparison operators in Python are used to compare values and determine the relationship between them. They return a Boolean value (True or False) based on the comparison result.

1. == (Equal to): Checks if two values are equal.
2. != (Not equal to): Checks if two values are not equal.
3. (Greater than): Checks if the left value is greater than the right value.
4. < (Less than): Checks if the left value is less than the right value.
5. = (Greater than or equal to): Checks if the left value is greater than or equal to the right value.
6. <= (Less than or equal to): Checks if the left value is less than or equal to the right value.

### Example of Comparison Operators in Python

``````# Comparison operators example
x = 10
y = 5

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

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

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

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

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

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

Output:

In this example, we have two variables x and y assigned with values 10 and 5, respectively. We then use different comparison operators (==, !=, >, <, >=, <=) to compare these values.

Each comparison operation returns a Boolean value (True or False) based on the comparison result. The output displays the result of each comparison operation.

``````Is x equal to y? False
Is x not equal to y? True
Is x greater than y? True
Is x less than y? False
Is x greater than or equal to y? True
Is x less than or equal to y? False
``````

## Logical operators in Python

Logical operators in Python are used to perform logical operations on Boolean values (True or False). They allow you to combine multiple conditions or invert the logical value of an expression.

1. and: Returns True if both the left and right expressions are True. Otherwise, it returns False.
2. or: Returns True if at least one of the left or right expressions is True. If both expressions are False, it returns False.
3. not: Inverts the logical value of an expression. If the expression is True, not returns False. If the expression is False, not returns True.

### Example of Logical operators in Python

``````# Logical operators example
x = 10
y = 5
z = 7

# and operator
result_and = (x > y) and (y < z)
print("Result of (x > y) and (y < z):", result_and)  # Output: True

# or operator
result_or = (x > y) or (y > z)
print("Result of (x > y) or (y > z):", result_or)  # Output: True

# not operator
result_not = not(x > y)
print("Result of not(x > y):", result_not)  # Output: False
``````

Output:

In this example, we have three variables `x`, `y`, and `z` assigned with values 10, 5, and 7, respectively. We use different logical operators (`and`, `or`, `not`) to perform logical operations on the given expressions.

The `and` operator checks if both the conditions `(x > y)` and `(y < z)` are True, and returns True only if both conditions are met. In this case, the result is True.

The `or` operator checks if at least one of the conditions `(x > y)` or `(y > z)` is True, and returns True if any of the conditions is True. In this case, the result is True because the first condition is True.

The `not` operator inverts the logical value of the expression `(x > y)`. Since the expression `(x > y)` is True, the `not` operator returns False.

``````Result of (x > y) and (y < z): True
Result of (x > y) or (y > z): True
Result of not(x > y): False
``````

## Bitwise Operators in Python

Bitwise operators in Python are used to perform operations at the binary level on individual bits of integers. These operators work by manipulating the binary representation of numbers.

1. & (Bitwise AND): Performs a bitwise AND operation between the corresponding bits of two numbers.
2. | (Bitwise OR): Performs a bitwise OR operation between the corresponding bits of two numbers.
3. ^ (Bitwise XOR): Performs a bitwise XOR (exclusive OR) operation between the corresponding bits of two numbers.
4. ~ (Bitwise NOT): Flips the bits of a number, resulting in the one’s complement.
5. << (Left Shift): Shifts the bits of a number to the left by a specified number of positions.
6. (Right Shift): Shifts the bits of a number to the right by a specified number of positions.

### Example of Bitwise Operators in Python

``````# Bitwise operators example
x = 10
y = 5

# Bitwise AND
result_and = x & y
print("Result of x & y (Bitwise AND):", result_and)  # Output: 0b0 (binary representation)

# Bitwise OR
result_or = x | y
print("Result of x | y (Bitwise OR):", result_or)  # Output: 0b1111 (binary representation)

# Bitwise XOR
result_xor = x ^ y
print("Result of x ^ y (Bitwise XOR):", result_xor)  # Output: 0b1111 (binary representation)

# Bitwise NOT
result_not_x = ~x
result_not_y = ~y
print("Result of ~x (Bitwise NOT x):", result_not_x)  # Output: -11
print("Result of ~y (Bitwise NOT y):", result_not_y)  # Output: -6

# Left Shift
result_left_shift = x << 2
print("Result of x << 2 (Left Shift):", result_left_shift)  # Output: 40

# Right Shift
result_right_shift = x >> 2
print("Result of x >> 2 (Right Shift):", result_right_shift)  # Output: 2
``````

Output:

In this example, we have two variables `x` and `y` assigned with values 10 and 5, respectively. We use different bitwise operators (`&`, `|`, `^`, `~`, `<<`, `>>`) to perform operations on these numbers.

The bitwise AND (`&`) operator performs a bitwise AND operation between the binary representations of `x` and `y`. The result is 0 in binary representation (`0b0`).

The bitwise OR (`|`) operator performs a bitwise OR operation between the binary representations of `x` and `y`. The result is 15 in binary representation (`0b1111`).

The bitwise XOR (`^`) operator performs a bitwise XOR operation between the binary representations of `x` and `y`. The result is 15 in binary representation (`0b1111`).

The bitwise NOT (`~`) operator flips the bits of the numbers `x` and `y`, resulting in their one’s complement.

The left shift (`<<`) operator shifts the bits of `x` to the left by 2 positions, resulting in the value 40.

The right shift (`>>`) operator shifts the bits of `x` to the right by 2 positions, resulting in the value 2.

``````Result of x & y (Bitwise AND): 0b0
Result of x | y (Bitwise OR): 0b1111
Result of x ^ y (Bitwise XOR): 0b1111
Result of ~x (Bitwise NOT x): -11
Result of ~y (Bitwise NOT y): -6
Result of x << 2 (Left Shift): 40
Result of x >> 2 (Right Shift): 2
``````

## Identity Operators in Python

Identity operators in Python are used to check if two objects have the same identity, i.e. if they refer to the same memory location. These operators evaluate to True or False based on the comparison result.

• is: Returns True if both objects have the same identity. It evaluates to False if the objects have different identities.
• is not: Returns True if both objects have different identities. It evaluates to False if the objects have the same identity.

### Example of Identity Operators in Python

``````x = 5
y = 5

if x is y:
print("x and y have the same identity.")
else:
print("x and y have different identities.")

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

if a is not b:
print("a and b have different identities.")
else:
print("a and b have the same identity.")
``````

Output:

In this code, we have two scenarios:

The variables `x` and `y` both hold the value 5. Since small integers in Python are often cached and reused, they have the same identity. Therefore, the output indicates that `x` and `y` have the same identity.

The variables `a` and `b` are two different lists, even though they contain the same values. Since they are separate objects in memory, they have different identities. Thus, the output states that `a` and `b` have different identities.

``````x and y have the same identity.
a and b have different identities.
``````

## Membership Operators in Python

Membership operators are used in programming to check if a value exists within a sequence, such as a list, tuple, or string. The two membership operators commonly used are “in” and “not in.

The “in” operator checks if a value is present in a sequence. It returns True if the value is found in the sequence and False if it is not.

### Example of Membership Operators in Python

``````fruits = ['apple', 'banana', 'orange']
numbers = [1, 2, 3, 4, 5]

if 'banana' in fruits:
print("Yes, 'banana' is in the list of fruits.")

if 6 not in numbers:
print("Yes, 6 is not in the list of numbers.")
``````

Output:

In this example, we have two separate:

The first if statement checks if the string ‘banana’ is present in the list of fruits using the “in” operator. Since ‘banana’ is an element in the list, the condition is True, and the corresponding message is printed.

The second if statement checks if the number 6 is not present in the list of numbers using the “not in” operator. 6 is not one of the elements in the list, the condition is True, and the corresponding message is printed.

```Yes, 'banana' is in the list of fruits.
Yes, 6 is not in the list of numbers.
```

## Example of Python Operators

``````# Arithmetic Operators
x = 5 + 3
y = 10 - 2
z = 2 * 4
w = 16 / 2
r = 17 % 3

# Comparison Operators
a = 7 > 5
b = 3 <= 10
c = 5 == 5
d = 8 != 9
e = 12 < 15

# Logical Operators
f = True and False
g = True or False
h = not True

# Assignment Operators
i = 2
i += 3
i -= 1
i *= 4
i /= 2

# Identity Operators
j = 5
k = 5
l = (j is k)
m = (j is not k)

# Membership Operators
fruits = ['apple', 'banana', 'orange']
n = 'banana' in fruits
o = 'grape' not in fruits

print(x, y, z, w, r)
print(a, b, c, d, e)
print(f, g, h)
print(i)
print(l, m)
print(n, o)
``````

Output:

```8 8 8 8.0 2
True True True True True
False True False
8.0
True False
True True```