# Understanding Basic Operators in Python

Python

As a beginner in Python programming, it’s crucial to understand the basic operators that form the backbone of numerous operations you’ll perform.

Operators are like the verbs in a language: they define actions performed on data. We’ll explore three primary categories: arithmetic, assignment, and comparison operators.

## Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.

#### Addition (`+`)

• Example: `a + b`
Python
``````a = 3
b = 2
sum = a + b  # sum is 5``````

#### Subtraction (`-`)

• Example: `a - b`
Python
``````a = 5
b = 2
difference = a - b  # difference is 3``````

#### Multiplication (`*`)

• Example: `a * b`
Python
``````a = 4
b = 3
product = a * b  # product is 12``````

#### Division (`/`)

• Example: `a / b`
Python
``````a = 12
b = 3
quotient = a / b  # quotient is 4.0 (note: result is a float)``````

#### Modulus (`%`)

The modulus operator in Python, denoted by `%`, is used to find the remainder when dividing one number by another.

It is a very useful operator in various programming scenarios, especially when you need to determine if a number is divisible by another or to handle periodic phenomena like wrapping around array indices.

Here are some examples to illustrate its use:

1. Finding Remainder
Python
``result = 7 % 3``

Here, `7 % 3` will return `1`, because when 7 is divided by 3, the remainder is 1.

1. Checking for Even/Odd Numbers
Python
``````number = 4
if number % 2 == 0:
print("Even")
else:
print("Odd")``````

This code checks if a number is even or odd. Since `4 % 2` equals 0, the number is even.

1. Cycling Through a Sequence
Python
``````colors = ['red', 'green', 'blue']
for i in range(10):
print(colors[i % len(colors)])``````

This code will repeatedly cycle through the list `colors`. The modulus operation ensures that the index `i` doesn’t exceed the length of the list, thus avoiding an `IndexError`.

1. Handling Time Calculations
Python
``````total_minutes = 123
hours = total_minutes // 60  # Integer division for total hours
minutes = total_minutes % 60  # Modulus for remaining minutes
print(f"{hours} hours and {minutes} minutes")``````

In this example, modulus is used to convert a total number of minutes into hours and minutes.

#### Exponentiation (`**`)

• Example: `a ** b`
Python
``````a = 3
b = 2
power = a ** b  # power is 9``````

#### Floor Division (`//`)

Floor division in Python is performed using the `//` operator. It divides two numbers and rounds down the result to the nearest whole number.

This operation is different from regular division (`/`), which returns a floating-point result including the decimal part. Here are some examples to illustrate the use of floor division:

1. Basic Floor Division
Python
``result = 7 // 3``

Here, `7 // 3` will return `2` because when 7 is divided by 3, the quotient is 2.33, which is rounded down to 2.

1. Negative Numbers
Python
``result = -7 // 3``

In this case, `-7 // 3` returns `-3`. This is because -7 divided by 3 is -2.33, and floor division rounds down to the next lower whole number, which is -3.

1. Combining with Modulus for Time Calculations
Python
``````total_minutes = 123
hours = total_minutes // 60  # Integer division for total hours
minutes = total_minutes % 60  # Modulus for remaining minutes
print(f"{hours} hours and {minutes} minutes")``````

Here, floor division is used to calculate the total hours from minutes, while modulus is used to find the remaining minutes.

1. Working with Arrays and Lists
Python
``````elements = [1, 2, 3, 4, 5, 6, 7, 8, 9]
middle_index = len(elements) // 2
middle_element = elements[middle_index]``````

This code finds the middle element of an array. The floor division ensures that the index is a whole number, which is necessary for indexing in a list.

## Assignment Operators

Assignment operators in Python are used to assign values to variables.

While the most common one is the simple `=` operator, Python also provides a variety of compound assignment operators that combine arithmetic or bitwise operations with assignment.

These make your code more concise and can sometimes improve readability. Here are some common examples:

1. Simple Assignment (`=`)
Python
``x = 10``

This is the basic assignment operator. It assigns the value `10` to the variable `x`.

1. Addition Assignment (`+=`)
Python
``x += 3  # Equivalent to x = x + 3``

This operator adds the right operand to the left operand and assigns the result to the left operand. Here, `x` would be `13` if `x` was initially `10`.

1. Subtraction Assignment (`-=`)
Python
``x -= 2  # Equivalent to x = x - 2``

Subtracts the right operand from the left operand and assigns the result to the left operand. If `x` was `10`, it now becomes `8`.

1. Multiplication Assignment (`*=`)
Python
``x *= 3  # Equivalent to x = x * 3``

Multiplies the left operand by the right operand and assigns the result to the left operand. If `x` was `10`, it now becomes `30`.

1. Division Assignment (`/=`)
Python
``x /= 2  # Equivalent to x = x / 2``

Divides the left operand by the right operand and assigns the result to the left operand. This is a floating-point division. If `x` was `10`, it now becomes `5.0`.

1. Floor Division Assignment (`//=`)
Python
``x //= 3  # Equivalent to x = x // 3``

Applies floor division and assigns the result to the left operand. If `x` was `10`, it now becomes `3`.

1. Modulus Assignment (`%=`)
Python
``x %= 4  # Equivalent to x = x % 4``

Calculates the modulus and assigns the result to the left operand. If `x` was `10`, it now becomes `2`.

1. Exponentiation Assignment (`**=`)
Python
``x **= 3  # Equivalent to x = x ** 3``

Raises the left operand to the power of the right operand and assigns the result to the left operand. If `x` was `10`, it now becomes `1000`.

1. Bitwise AND Assignment (`&=`)
Python
``x &= 7  # Equivalent to x = x & 7``
1. Bitwise OR Assignment (`|=`)
Python
``x |= 3  # Equivalent to x = x | 3``

Performs a bitwise OR operation and assigns the result to the left operand.

These compound assignment operators are essentially shorthand for the longer form of the operation, simplifying the syntax especially in cases where the same variable is modified and then updated.

## Comparison Operators

Comparison operators in Python are used to compare values. They return a Boolean value (`True` or `False`) based on the condition being tested.

These operators are fundamental to decision-making in Python, as they are extensively used in control flow statements like `if`, `while`, and `for`. Here are the main comparison operators in Python:

1. Equal To (`==`)
Python
``x == y``

Returns `True` if the values of `x` and `y` are equal, `False` otherwise.

1. Not Equal To (`!=`)
Python
``x != y``

Returns `True` if `x` and `y` are not equal, `False` if they are.

1. Greater Than (`>`)
Python
``x > y``

Returns `True` if `x` is greater than `y`, `False` otherwise.

1. Less Than (`<`)
Python
``x < y``

Returns `True` if `x` is less than `y`, `False` otherwise.

1. Greater Than or Equal To (`>=`)
Python
``x >= y``

Returns `True` if `x` is greater than or equal to `y`, `False` otherwise.

1. Less Than or Equal To (`<=`)
Python
``x <= y``

Returns `True` if `x` is less than or equal to `y`, `False` otherwise.

Here are a few examples to illustrate their use:

• `4 == 4` would return `True` because 4 is equal to 4.
• `3 != 5` would return `True` because 3 is not equal to 5.
• `6 > 2` would return `True` because 6 is greater than 2.
• `7 < 10` would return `True` because 7 is less than 10.
• `8 >= 8` would return `True` because 8 is equal to 8 (and thus also greater than or equal to 8).
• `9 <= 11` would return `True` because 9 is less than 11.

These operators are crucial for various logical operations and form the basis of much of the decision-making logic in programming.

## Order of Operations in Python

In Python, the order of operations, also known as precedence, determines the sequence in which operators are evaluated in expressions. Here’s the standard order, from highest to lowest precedence:

1. Parentheses `()`: Expressions inside parentheses are evaluated first. This can be used to override the default order of operations.
2. Exponentiation `**`: Next, Python evaluates exponentiation.
3. Unary Plus and Minus `+x`, `-x`: This step includes unary operations like positive and negative signs.
4. Multiplication `*`, Division `/`, Floor Division `//`, Modulus `%`: These operators are evaluated next. They have the same level of precedence, so Python evaluates them from left to right.
5. Addition `+` and Subtraction `-`: These operators are evaluated after the above operators. They also have the same level of precedence and are evaluated from left to right.
6. Bitwise Shifts `<<`, `>>`: These are evaluated next.
7. Bitwise AND `&`: After bitwise shifts, bitwise AND is evaluated.
8. Bitwise XOR `^`: This follows bitwise AND.
9. Bitwise OR `|`: This is evaluated after bitwise XOR.
10. Comparison Operators `==`, `!=`, `<`, `<=`, `>`, `>=`, `is`, `is not`, `in`, `not in`: These operators have lower precedence and are evaluated next.
11. Boolean NOT `not`: This unary operator has lower precedence than comparison operators.
12. Boolean AND `and`: This is evaluated after boolean NOT.
13. Boolean OR `or`: This has the lowest precedence and is evaluated last.

It’s important to note that operators with the same precedence level are generally evaluated from left to right, except for exponentiation, which is evaluated from right to left. Using parentheses to group expressions is a good practice for making code more readable and ensuring that operations are performed in the intended order.

## Conclusion

By understanding and practicing these basic operators in Python, you will be able to perform a wide range of operations, from simple arithmetic to complex comparisons.

These are the building blocks upon which more advanced programming concepts are built.

Remember, practice is key, so experiment with these operators and try creating your own examples to gain a deeper understanding.