WcBma5LrLOg50X66kF3p5HaCfJ41Lo99JHjSF8cx
Bookmark

# Python Operators Precedence

In Python, operator precedence determines the order in which different operators are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence. If operators have the same precedence, their evaluation order depends on their associativity (left-to-right or right-to-left).

Here is a summary of Python's operator precedence from highest to lowest, along with some examples:

### 1. Parentheses

Parentheses are used in expressions to explicitly specify the order in which operations are performed. When parentheses are used, the expressions within the parentheses are evaluated before the surrounding operations. This can override the default operator precedence. Here are some examples to illustrate:

#### a. Without Parentheses

``result = 3 + 4 * 5``
Here, multiplication has higher precedence than addition, so `4 * 5` is evaluated first, and then the result is added to 3. The result will be 23.

#### b. With Parentheses

``result = (3 + 4) * 5``
By using parentheses, we ensure that the addition operation is performed first, resulting in 7, and then the multiplication is performed, resulting in 35.

#### c. Nested Parentheses

``result = ((2 + 3) ** 2) / (4 + 1)``
Here, the inner set of parentheses are evaluated first: `2 + 3` results in 5, and then `5 ** 2` results in 25. The outer set of parentheses `(4 + 1)` results in 5. Finally, the division operation is performed, resulting in 25 / 5 = 5.

#### d. Mixing Parentheses and Operators

``result = 2 * (4 + 3) ** 2``
In this case, the expression within the inner parentheses `(4 + 3)` is evaluated first, resulting in 7. Then, `7 ** 2` results in 49. Finally, the multiplication operation is performed, resulting in 2 * 49 = 98.

Remember that using parentheses not only clarifies the order of operations but also makes the code more readable and reduces the chance of confusion. It's a good practice to use parentheses liberally in complex expressions to ensure that the calculations are carried out as intended.

### 2. Exponentiation

Exponentiation is the mathematical operation of raising a base number to a certain power. In Python, the exponentiation operator `**` is used to perform this operation. The expression `a ** b` calculates `a` raised to the power of `b`. Here are some examples:

#### a. Basic Exponentiation

``result = 2 ** 3``
In this case, `2` is raised to the power of `3`, resulting in `8`.

#### b. Chained Exponentiation

``result = 2 ** 3 ** 2``
The exponentiation operation is right-associative, meaning it evaluates from right to left. So, `3 ** 2` is calculated first, resulting in `9`, and then `2 ** 9` is calculated, resulting in `512`.

#### c. Exponentiation with Negative Exponents

``result = 10 ** -2``
Raising a number to a negative exponent is equivalent to taking the reciprocal of the number raised to the positive exponent. So, `10 ** -2` is equivalent to `1 / (10 ** 2)`, resulting in `0.01`.

#### d. Exponentiation with Fractional Exponents

``result = 16 ** 0.5``
Raising a number to a fractional exponent corresponds to finding the root of the number. Here, `16 ** 0.5` calculates the square root of `16`, which is `4`.

#### e. Exponentiation and Parentheses

``result = (2 + 3) ** 2``
Here, the expression within the parentheses is evaluated first: `2 + 3` results in `5`. Then, `5 ** 2` calculates `25`.

Exponentiation can be used in various mathematical and scientific calculations, as well as in algorithms involving growth and decay, such as compound interest calculations. It's important to be aware of operator precedence when using exponentiation in combination with other operators in more complex expressions to ensure that the calculations are performed as intended.

### 3. Multiplication, Division, Modulus

#### a. Multiplication

Multiplication is the mathematical operation of repeated addition. In Python, the `*` operator is used for multiplication. It calculates the product of two numbers.

``result = 3 * 4``

In this case, `3` multiplied by `4` results in `12`.

#### b. Division

Division is the operation of distributing a quantity into equal parts. In Python, the `/` operator is used for division. It calculates the quotient of dividing one number by another.

``result = 10 / 2``

Here, `10` divided by `2` results in `5.0`. Note that in Python 3, even if the result is a whole number, division using the `/` operator will produce a floating-point result.

#### c. Floor Division

Floor division is similar to regular division, but it rounds the result down to the nearest integer. The `//` operator is used for floor division.

``result = 10 // 3``

The floor division of `10` by `3` results in `3`. The fractional part of the division is discarded.

#### d. Modulus

The modulus operation calculates the remainder when one number is divided by another. In Python, the `%` operator is used for the modulus operation.

``result = 10 % 3``

Here, the modulus of `10` divided by `3` results in `1`. This is the remainder left when `10` is divided by `3`.

#### e. Combined Operations

``result = (5 + 3) * 4 / 2 % 3``

Here, the expression is evaluated step by step:

1. `(5 + 3)` results in `8`
2. `8 * 4` results in `32`
3. `32 / 2` results in `16.0`
4. `16.0 % 3` results in `1.0`

These operations are fundamental in mathematical calculations and are widely used in various programming tasks, ranging from simple arithmetic to more complex algorithms and data manipulation tasks. Understanding the behavior of these operations and their precedence in Python expressions is crucial for writing accurate and efficient code.

Addition is a basic mathematical operation that combines two or more numbers to obtain a total sum. In Python, the `+` operator is used for addition.

``result = 5 + 3``

Here, `5` added to `3` results in `8`.

#### b. Subtraction

Subtraction involves taking away one quantity from another. In Python, the `-` operator is used for subtraction.

``result = 10 - 4``

The subtraction of `4` from `10` results in `6`.

#### c. Chained Addition and Subtraction

``result = 10 + 5 - 2``
In this case, the addition and subtraction operations are evaluated from left to right. `10 + 5` results in `15`, and then `15 - 2` results in `13`.

#### d. Mixed with Other Operators

``result = 2 * (8 + 4) - 3``
Here, the expression within the parentheses is evaluated first: `8 + 4` results in `12`. Then, `2 * 12` results in `24`. Finally, `24 - 3` results in `21`.

``result = 3.5 + 1.2``
Floating-point numbers (decimal numbers) can also be added together using the `+` operator. The result in this case is `4.7`.

Addition and subtraction are fundamental arithmetic operations that are used extensively in programming for calculations, logic, and data manipulation. Understanding the behavior of these operators and their precedence in Python expressions is essential for writing correct and effective code.

### 5. Bitwise Shifts

Bitwise shifts are operations that manipulate the individual bits of integers. In Python, there are two types of bitwise shift operators: left shift (`<<`) and right shift (`>>`). These operators move the bits of an integer to the left or right by a specified number of positions.

#### a. Left Shift (<<)

The left shift operator shifts the bits of an integer to the left by a specified number of positions. This operation effectively multiplies the integer by 2 raised to the power of the specified shift amount.

``result = 7 << 2``

Here, the binary representation of `7` is `0111`. When shifted left by `2` positions, it becomes `1100`, which is `12` in decimal.

#### b. Right Shift (>>)

The right shift operator shifts the bits of an integer to the right by a specified number of positions. This operation effectively divides the integer by 2 raised to the power of the specified shift amount, while discarding any remainder.

``result = 16 >> 3``

The binary representation of `16` is `10000`. When shifted right by `3` positions, it becomes `00010`, which is `2` in decimal.

#### c. Negative Numbers and Right Shift

When dealing with negative numbers, the behavior of the right shift operator might vary depending on the implementation and the specific use case. Python uses arithmetic right shift, which preserves the sign of the number.

``result = -16 >> 2``

The binary representation of `-16` is platform-dependent, but let's assume it's something like `11111111111111111111111111110000`. When shifted right by `2` positions, it becomes `11111111111111111111111111111100`, which, as a two's complement representation, corresponds to `-4`.

Bitwise shifts are used in low-level programming, such as working with binary data and optimizing certain algorithms. They can also have applications in creating efficient data structures and implementing various numerical operations. Understanding bitwise operations is crucial when working with these types of tasks.

### 6. Bitwise AND

Bitwise AND is an operation that performs a logical AND operation on each pair of corresponding bits of two integers. The result is a new integer where each bit is set to 1 only if the corresponding bits in both operands are also 1. Otherwise, the result bit is set to 0.

In Python, the bitwise AND operator is represented by the `&` symbol. Here's how the bitwise AND operation works:

#### a. Bitwise AND of Positive Integers

``result = 14 & 7``
The binary representation of `14` is `1110`, and the binary representation of `7` is `0111`. When performing a bitwise AND operation, the result will be `0110`, which is `6` in decimal.

#### b. Bitwise AND of Negative and Positive Integers

``result = -10 & 5``
Let's assume that `-10` is represented in two's complement form as `...11110110`. The binary representation of `5` is `00000101`. Performing bitwise AND yields `00000100`, which is `4` in decimal.

#### c. Bitwise AND with Zero

``result = 15 & 0``
The result of a bitwise AND operation with `0` will always be `0`, regardless of the other operand.

#### d. Bitwise AND and Masking

``````flags = 0b11001110
Here, `flags` has a binary representation of `11001110`, and `mask` has a binary representation of `00110000`. The result of the bitwise AND operation is `00000000`, which corresponds to clearing out certain bits using the mask.

Bitwise AND operations are used for a variety of purposes, such as manipulating individual bits in a number, extracting specific bit patterns, and creating bitmasks for various purposes, including data manipulation, hardware control, and more.

### 7. Bitwise XOR

Bitwise XOR is an operation that performs a logical XOR operation on each pair of corresponding bits of two integers. The result is a new integer where each bit is set to 1 if the corresponding bits in the operands are different (one is 0 and the other is 1).

If the corresponding bits are the same (both 0 or both 1), the result bit is set to 0. In Python, the bitwise XOR operator is represented by the `^` symbol. Here's how the bitwise XOR operation works:

#### a. Bitwise XOR of Positive Integers

``result = 15 ^ 6``
The binary representation of `15` is `1111`, and the binary representation of `6` is `0110`. When performing a bitwise XOR operation, the result will be `1001`, which is `9` in decimal.

#### b. Bitwise XOR of Negative and Positive Integers

``result = -10 ^ 5``
Let's assume that `-10` is represented in two's complement form as `...11110110`. The binary representation of `5` is `00000101`. Performing bitwise XOR yields `11110011`, which corresponds to `-13` in decimal.

#### c. Bitwise XOR with Zero

``result = 10 ^ 0``
The result of a bitwise XOR operation with `0` will always be the same as the original number, as XORing with `0` has no effect.

#### d. Bitwise XOR and Toggle Bits

``````flags = 0b11001100
Here, `flags` has a binary representation of `11001100`, and `toggle_mask` has a binary representation of `00110000`. The result of the bitwise XOR operation is `11111100`, which corresponds to toggling specific bits using the mask.

Bitwise XOR operations are used for various purposes, including toggling specific bits, flipping individual bits, and data encryption/decryption. They are also employed in error detection and correction algorithms, as well as in certain arithmetic calculations and data manipulation tasks.

### 8. Bitwise OR

Bitwise OR is an operation that performs a logical OR operation on each pair of corresponding bits of two integers. The result is a new integer where each bit is set to 1 if at least one of the corresponding bits in the operands is 1. If both corresponding bits are 0, the result bit is set to 0.

In Python, the bitwise OR operator is represented by the | symbol. Here's how the bitwise OR operation works:

#### a. Bitwise OR of Positive Integers

``result = 14 | 7``
The binary representation of `14` is `1110`, and the binary representation of `7` is `0111`. When performing a bitwise OR operation, the result will be `1111`, which is `15` in decimal.

#### b. Bitwise OR of Negative and Positive Integers

``result = -10 | 5``
Let's assume that `-10` is represented in two's complement form as `...11110110`. The binary representation of `5` is `00000101`. Performing bitwise OR yields `...11110111`, which corresponds to `-9` in decimal.

#### c. Bitwise OR with Zero

``result = 15 | 0``
The result of a bitwise OR operation with `0` will always be the same as the original number, as ORing with `0` has no effect.

#### d. Bitwise OR and Setting Bits

``````flags = 0b11001100
Here, `flags` has a binary representation of `11001100`, and `set_mask` has a binary representation of `00110000`. The result of the bitwise OR operation is `11111100`, which corresponds to setting specific bits using the mask.

Bitwise OR operations are used for various purposes, including setting specific bits, combining individual flags or attributes, and data manipulation tasks where certain bits need to be activated. They are also used in computer graphics, cryptography, and low-level programming tasks.

### 9. Comparison Operators

Comparison operators are used to compare two values or expressions and determine the relationship between them. These operators return a Boolean value (`True` or `False`) based on the comparison result. Here are the main comparison operators in Python:

#### a. Equal (==)

The equal operator checks if two values are equal.

``result = 5 == 5  # True``

#### b. Not Equal (!=)

The not equal operator checks if two values are not equal.

``result = 5 != 3  # True``

#### c. Greater Than (>)

The greater than operator checks if the left operand is greater than the right operand.

``result = 8 > 6  # True``

#### d. Less Than (<)

The less than operator checks if the left operand is less than the right operand.

``result = 3 < 5  # True``

#### e. Greater Than or Equal To (>=)

The greater than or equal to operator checks if the left operand is greater than or equal to the right operand.

``result = 7 >= 7  # True``

#### f. Less Than or Equal To (<=)

The less than or equal to operator checks if the left operand is less than or equal to the right operand.

``result = 4 <= 4  # True``

Comparison operators are frequently used in conditional statements, loops, and filtering data based on specific conditions. For instance, they are used in `if` statements to make decisions based on whether a certain condition is met, and they play a crucial role in sorting algorithms and searching algorithms.

The results of comparison operators are boolean values, which can be used to control the flow of a program or make logical decisions based on the relationships between values.

### 10. Membership Operators

Membership operators are used to test whether a value is a member of a sequence, such as a string, list, tuple, or set. These operators return a Boolean value (`True` or `False`) based on whether the tested value is present in the sequence.

Python provides two membership operators:

#### a. `in` Operator

The `in` operator checks whether a value exists in a sequence.

``result = 3 in [1, 2, 3, 4]  # True``

#### b. `not in` Operator

The `not in` operator checks whether a value does not exist in a sequence.

``result = 'apple' not in ['banana', 'orange', 'grape']  # True``

Membership operators are often used in conditional statements and loops to check if an element is present in a collection before taking a specific action.

They are particularly useful when searching through lists, strings, and other iterable objects. Additionally, they can help filter or process data based on specific criteria, such as finding specific items in a list or checking for the presence of certain characters in a string.

### 11. Assignment Operators

Assignment operators are used to assign values to variables. They allow you to update the value of a variable based on an operation or expression. Assignment operators combine an arithmetic or other operation with the assignment of the result to a variable in a single statement.

Here are some common assignment operators in Python:

#### a. Assignment (=) Operator

The basic assignment operator assigns the value on the right-hand side to the variable on the left-hand side.

``x = 5``

#### b. Addition Assignment (+=) Operator

The addition assignment operator adds the value on the right-hand side to the current value of the variable on the left-hand side and updates the variable.

``x += 3  # Equivalent to x = x + 3``

#### c. Subtraction Assignment (-=) Operator

The subtraction assignment operator subtracts the value on the right-hand side from the current value of the variable on the left-hand side and updates the variable.

``y -= 2  # Equivalent to y = y - 2``

#### d. Multiplication Assignment (*=) Operator

The multiplication assignment operator multiplies the value on the right-hand side by the current value of the variable on the left-hand side and updates the variable.

``z *= 4  # Equivalent to z = z * 4``

#### e. Division Assignment (/=) Operator

The division assignment operator divides the current value of the variable on the left-hand side by the value on the right-hand side and updates the variable.

``w /= 2  # Equivalent to w = w / 2``

#### f. Modulus Assignment (%=) Operator

The modulus assignment operator calculates the remainder of dividing the current value of the variable on the left-hand side by the value on the right-hand side and updates the variable.

``n %= 5  # Equivalent to n = n % 5``

#### g. Exponentiation Assignment (**=) Operator

The exponentiation assignment operator raises the current value of the variable on the left-hand side to the power of the value on the right-hand side and updates the variable.

``m **= 3  # Equivalent to m = m ** 3``

Assignment operators are used extensively in Python to perform calculations and update variables efficiently. They combine an operation with the assignment step, reducing the need for multiple lines of code and making the code more concise and readable.

Posting Komentar