# Python Basics: Operators

Operators are symbols or keywords that perform various operations on one or more values. They are fundamental building blocks for manipulating data, performing calculations, and making comparisons in programs.

For more posts about Python, follow the link below.πππ

In the previous post, we discussed basic types like integers and performed some operations on them using different **operators**. That gave us a brief taste of what operators are in Python and enabled us to explore even more that matter.

If you feel like you need a refresher on basic types, you can find it by following the link. πππ

## Intro

Operators in Python are symbols or special keywords that perform various operations on variables and values. Here are some of the most common types of operators that can be found in Python:

Operators type | Description |
---|---|

Arithmetic | Perform basic mathematical operations |

Assignment | Assign values to variables |

Bitwise | Perform bitwise operations on integers |

Comparison | Compare two values and return a boolean result |

Identity | Compare the memory location of two objects |

Logical | Combine boolean values or expressions |

Membership | Check if a value is present in a sequence |

These fundamental types of operators allow you to perform a wide range of operations on variables and values to achieve different tasks.

## Arithmetic operators

Arithmetic operators provide an ability to perform basic mathematical operations in Python.

**Addition ( +)** operator takes two numeric values and returns their sum.

```
>>> a = 3
>>> b = 5
>>> result = a + b
>>> print(result)
8
```

**Subtraction ( -)** operator takes two numeric values and returns the difference between the first and the second - it subtracts the second number from the first.

```
>>> a = 10
>>> b = 4
>>> result = a - b
>>> print(result)
6
```

**Multiplication ( *)** operator takes two numeric values and returns their product - it multiplies two numbers.

```
>>> a = 3
>>> b = 7
>>> result = a * b
>>> print(result)
21
```

**Division ( /)** operator performs floating-point division, it divides the first number by the second, resulting in a floating-point value.

```
>>> a = 15
>>> b = 4
>>> result = a / b
>>> print (result)
3.75
```

**Modulo ( %)** operator calculates the remainder when dividing the first value by the second value.

```
>>> a = 17
>>> b = 5
>>> result = a % b
>>> print (result)
2
```

**Exponentiation ( **)** calculates the value of the first number raised to the power of the second number.

```
>>> a = 2
>>> b = 3
>>> result = a ** b
>>> print(result)
8
```

**Floor Division ( //)** operator calculates the quotient - it divides the first number by the second and rounds down to the nearest integer.

```
>>> a = 17
>>> b = 5
>>> result = a // b
>>> print(result)
3
```

Arithmetic operators are crucial for performing mathematical calculations. They provide the basic building blocks for working with numbers.

## Assignment operators

Assignment operators provide the ability to update a variable's value.

**Assignment ( =)** operator is used to assign the value on the right side to the variable on the left side.

```
>>> x = 10
>>> print(x)
10
```

**Add and Assign ( +=) **operator updates the value of a variable by adding a specified value to it. It adds the right operand to the left operand and assigns the result to the left operand.

```
>>> x = 5
>>> x += 3
>>> print(x)
8
```

**Subtract and Assign ( -=)** operator updates the value of a variable by subtracting a specified value from it. The operator subtracts the right operand from the left operand and assigns the result to the left operand.

```
>>> x = 10
>>> x -= 4
>>> print(x)
6
```

**Multiply and Assign ( *=)** operator updates the value of a variable by multiplying it with a specified value. It multiplies the left operand by the right operand and assigns the result to the left operand.

```
>>> x = 3
>>> x *= 2
>>> print(x)
6
```

**Divide and Assign ( /=)** operator updates the value of a variable by dividing it by a specified value. It divides the left operand by the right operand and assigns the result to the left operand.

```
>>> x = 15
>>> x /= 3
>>> print(x)
5.0
```

**Modulo and Assign ( %=)** operator updates the value of a variable with the remainder after division. It computes the modulo (remainder) of the left operand divided by the right operand and assigns the result to the left operand.

```
>>> x = 17
>>> x %= 5
>>> print(x)
2
```

**Exponentiation and Assign ( **=)** operator updates the value of a variable by exponentiating it with a specified value. It raises the left operand to the power of the right operand and assigns the result to the left operand.

```
>>> x = 2
>>> x **= 3
>>> print(x)
8
```

**Floor Division and Assign ( //=)** operator updates the value of a variable with the result of floor division. It performs floor division on the left operand and assigns the result to the left operand.

```
>>> x = 17
>>> x //= 5
>>> print(x)
3
```

**Walrus operator ( :=)** assigns a value to a variable and then returns that value. This can be especially useful in situations where you want to both use a value and assign it to a variable. It is often used in contexts where you want to avoid computing a value multiple times or improve code readability by combining assignment and usage in a single line.

```
>>> x = 1
>>> print(x)
1
>>> print(x := 3)
3
>>> print(x)
3
```

Assignment operators provide a concise way to both perform an operation and update the value of a variable in a single step. They are often used to streamline code and make it more readable.

## Bitwise operators

Bitwise operators are used to manipulate individual bits of integer values. They perform operations at the binary level, treating values as sequences of bits (zeros and ones).

**or**

**0b****prefix.**

**0B**For instance, number 2 can be expressed in binary format as 10.

```
>>> x = 0b10
>>> print (x)
2
```

*function.*

*bin()*```
>>> x = 2
>>> print(bin(x))
0b10
```

Understanding binary notation is crucial when dealing with bitwise operations.

**Bitwise AND ( &) ** operator performs a bitwise AND operation on corresponding bits of two integers. The result has a 1 only if both bits being compared are 1.

```
>>> a = 0b1100
>>> print(a)
12
>>> print(bin(a))
0b1100
>>> b = 0b0111
>>> print(b)
7
>>> print(bin(b))
0b111
>>> result = a & b
>>> print(result)
4
>>> print(bin(result))
0b100
```

**Bitwise OR ( |)** operator performs a bitwise OR operation on corresponding bits of two integers. The result has a 1 if at least one of the bits being compared is 1.

```
>>> a = 0b1100
>>> print(a)
12
>>> print(bin(a))
0b1100
>>> b = 0b0111
>>> print(b)
7
>>> print(bin(b))
0b111
>>> result = a | b
>>> print(result)
15
>>> print(bin(result))
0b1111
```

**Bitwise XOR ( ^) **operator

**performs a bitwise XOR (exclusive OR) operation on corresponding bits of two integers. The result has a 1 if the bits being compared are different (one 0 and one 1).**

```
>>> a = 0b1100
>>> print(a)
12
>>> print(bin(a))
0b1100
>>> b = 0b0111
>>> print(b)
7
>>> print(bin(b))
0b111
>>> result = a ^ b
>>> print(result)
11
>>> print(bin(result))
0b1011
```

**Bitwise NOT ( ~) **operator inverts the bits of an integer, changing 0s to 1s and 1s to 0s. It effectively calculates the two's complement of the number minus one.

```
>>> a = 0b1100
>>> print(a)
12
>>> print(bin(a))
0b1100
>>> result = ~a
>>> print(result)
-13
>>> print(bin(result))
-0b1101
```

**Left Shift ( <<)** operator shifts the bits of an integer to the left by a specified number of positions. Zeros are shifted in from the right, and the leftmost bits are discarded.

```
>>> a = 0b1100
>>> print(a)
12
>>> print(bin(a))
0b1100
>>> result = a << 2
>>> print(result)
48
>>> print(bin(result))
0b110000
```

**Right Shift ( >>) operator **shifts the bits of an integer to the right by a specified number of positions. The rightmost bits are discarded, and for signed numbers, the sign bit is preserved.

```
>>> print(a)
12
>>> print(bin(a))
0b1100
>>> result = a >> 2
>>> print(result)
3
>>> print(bin(result))
0b11
```

Bitwise operators are particularly useful for tasks that involve manipulating individual bits, such as working with low-level data representations, optimization, and encryption algorithms.

## Comparison operators

Comparison operators are used to compare values or expressions and return a Boolean result (`True`

or `False`

) based on the comparison.

**Equal to ( ==)** operator checks if two values are equal. It returns

`True`

if both values are the same.```
>>> a = 5
>>> b = 5
>>> result = a == b
>>> print(a, b, result)
5 5 True
>>> b = 6
>>> result = a == b
>>> print(a, b, result)
5 6 False
```

**Not equal to ( !=)** operator checks if two values are not equal. It returns

`True`

if the values are different.```
>>> a = 5
>>> b = 5
>>> result = a != b
>>> print(a, b, result)
5 5 False
>>> b = 6
>>> result = a != b
>>> print(a, b, result)
5 6 True
```

**Less than ( <)** operator checks if the left value is less than the right value. It returns

`True`

if the left value is smaller than the right value.```
>>> a = 5
>>> b = 5
>>> result = a < b
>>> print(a, b, result)
5 5 False
>>> b = 6
>>> result = a < b
>>> print(a, b, result)
5 6 True
```

**Greater than ( >)** operator checks if the left value is greater than the right value. It returns

`True`

if the left value is larger than the right value.```
>>> a = 5
>>> b = 5
>>> result = a > b
>>> print(a, b, result)
5 5 False
>>> b = 6
>>> result = a > b
>>> print(a, b, result)
5 6 False
```

**Less than or equal to ( <=) **operator checks if the left value is less than or equal to the right value. It returns

`True`

if the left value is smaller or equal to the right value.```
>>> a = 5
>>> b = 5
>>> result = a <= b
>>> print(a, b, result)
5 5 True
>>> b = 6
>>> result = a <= b
>>> print(a, b, result)
5 6 True
>>> b = 4
>>> result = a <= b
>>> print(a, b, result)
5 4 False
```

**Greater than or equal to ( >=)** operator checks if the left value is greater than or equal to the right value. It returns

`True`

if the left value is larger or equal to the right value.```
>>> a = 5
>>> b = 5
>>> result = a >= b
>>> print(a, b, result)
5 5 True
>>> b = 6
>>> result = a >= b
>>> print(a, b, result)
5 6 False
```

Comparison operators are fundamental for making decisions in your code based on the relationships between values. They are used extensively in conditions, loops, and other control flow structures.

## Identity operators

Identity operators are used to compare the memory locations of two objects, indicating whether they refer to the same object in memory or not, rather than comparing their values. They are particularly useful when working with mutable objects like lists, dictionaries, and instances of custom classes.

**Identity ( is)** operator checks if two variables refer to the same object in memory. It returns

`True`

if the memory location of both variables is the same.```
>>> x = [1, 2, 3]
>>> y = x
>>> result = x is y
>>> print(result)
True
```

**Negated Identity ( is not) **operator checks if two variables do not refer to the same object in memory. Returns

`True`

if the memory location of both variables is different.```
>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> result = x is not y
>>> print(result)
True
```

Identity operators are useful when you want to compare objects by reference rather than by their content. They help you determine whether two variables point to the same object or not.

## Logical operators

Logical Operators in Python are used to combine or manipulate Boolean values (`True`

or `False`

). They allow you to create more complex conditions by joining multiple conditions together.

**Logical AND ( and) **operator returns

`True`

if __both__operands, the left-hand side and the right-hand side are

`True`

, otherwise returns `False`

.```
>>> True and True
True
>>> True and False
False
>>> False and False
False
```

**Logical OR ( or) **operator returns

`True`

if __at least one__operand is

`True`

, otherwise returns `False`

.```
>>> True or True
True
>>> True or False
True
>>> False or False
False
```

**Logical NOT ( not)** operator

__negates__the value of a condition. It returns the opposite Boolean value of the operand.

```
>>> not True
False
>>> not False
True
```

Logical operators are essential for controlling the flow of your program based on different combinations of conditions. They help you create more sophisticated decision-making logic.

## Operator precedence

Operator precedence determines the order in which operators are evaluated when an expression contains multiple operators. It ensures that expressions are evaluated correctly by following a set of rules.** **The operators' priority order is as follows:

- Parentheses
`()`

: Highest precedence. Expressions within parentheses are evaluated first. - Exponentiation
`**`

- Multiplication
`*`

, Division`/`

, Floor Division`//`

, Modulo`%`

: These operators are evaluated from left to right. - Addition
`+`

, Subtraction`-`

: These operators are evaluated from left to right. - Bitwise Shift
`<<`

,`>>`

: These operators are evaluated from left to right. - Bitwise AND
`&`

- Bitwise XOR
`^`

- Bitwise OR
`|`

- Comparison Operators (
`<`

,`<=`

,`>`

,`>=`

,`==`

,`!=`

): These are evaluated from left to right. - Logical NOT
`not`

- Logical AND
`and`

- Logical OR
`or`

Here is an example of addition and multiplication operators being used. It can be easily noticed that using brackets totally changes a result.

```
>>> result = 3 + 5 * 2
>>> print(result)
13
>>> result = (3 + 5) * 2
>>> print(result)
16
```

Understanding operator precedence is crucial for writing accurate and predictable code. If you're unsure about the order of evaluation, you can use parentheses to explicitly define the order.

# What's next?

Subscribe to receive more posts like this directly to your email!

**Ideasπ‘, questionsββ ? Feel free to start the discussion π£οΈποΈ!**

Ready for challenges? πππ

## Comments ()