Python3 Basic Operators
# Python3 Operators
## Python3.x Python3 Operators
* * *
## What are Operators?
This chapter mainly explains Python's operators.
A simple example:
4 + 5 = 9
In the example, **4** and **5** are called **operands**, and + is called an **operator**.
Python supports the following types of operators:
Next, let's learn Python's operators one by one.
* * *
## Python Arithmetic Operators
The following assumes variable a=10 and variable b=21:
| Operator | Description | Example |
| --- | --- | --- |
| + | Addition - Adds two objects | a + b outputs 31 |
| - | Subtraction - Gives the negative of a number or subtracts one number from another | a - b outputs -11 |
| * | Multiplication - Multiplies two numbers or returns a string repeated several times | a * b outputs 210 |
| / | Division - x divided by y | b / a outputs 2.1 |
| % | Modulus - Returns the remainder of division | b % a outputs 1 |
| ** | Exponentiation - Returns x to the power of y | a**b is 10 to the power of 21 |
| // | Floor Division - Divides and rounds down to the nearest integer | >>> 9//24>>> -9//2-5 |
The following examples demonstrate the operations of all Python arithmetic operators:
## Example (Python 3.0+)
```python
a = 21
b = 10
c = 0
c = a + b
print("1 - Value of c: ", c)
c = a - b
print("2 - Value of c: ", c)
c = a * b
print("3 - Value of c: ", c)
c = a / b
print("4 - Value of c: ", c)
c = a % b
print("5 - Value of c: ", c)
a = 2
b = 3
c = a**b
print("6 - Value of c: ", c)
a = 10
b = 5
c = a//b
print("7 - Value of c: ", c)
The output of the above example:
1 - Value of c: 31
2 - Value of c: 11
3 - Value of c: 210
4 - Value of c: 2.1
5 - Value of c: 1
6 - Value of c: 8
7 - Value of c: 2
* * *
## Python Comparison Operators
The following assumes variable a is 10 and variable b is 20:
| Operator | Description | Example |
| --- | --- | --- |
| == | Equal - Compares if two objects are equal | (a == b) returns False. |
| != | Not Equal - Compares if two objects are not equal | (a != b) returns True. |
| > | Greater Than - Returns if x is greater than y | (a > b) returns False. |
| < | Less Than - Returns if x is less than y. All comparison operators return 1 for true, 0 for false. This is equivalent to the special variables True and False, respectively. Note the capitalization of these variable names. | (a = | Greater Than or Equal To - Returns if x is greater than or equal to y. | (a >= b) returns False. |
| <= | Less Than or Equal To - Returns if x is less than or equal to y. | (a <= b) returns True. |
The following examples demonstrate the operations of all Python comparison operators:
## Example (Python 3.0+)
```python
a = 21
b = 10
c = 0
if (a == b):
print("1 - a is equal to b")
else:
print("1 - a is not equal to b")
if (a != b):
print("2 - a is not equal to b")
else:
print("2 - a is equal to b")
if (a b):
print("4 - a is greater than b")
else:
print("4 - a is not greater than b")
a = 5
b = 20
if (a = a):
print("6 - b is greater than or equal to a")
else:
print("6 - b is not greater than or equal to a")
The output of the above example:
1 - a is not equal to b
2 - a is not equal to b
3 - a is not less than b
4 - a is not greater than b
5 - a is less than or equal to b
6 - b is greater than or equal to a
* * *
## Python Assignment Operators
The following assumes variable a is 10 and variable b is 20:
| Operator | Description | Example |
| --- | --- | --- |
| = | Simple assignment operator | c = a + b assigns the result of a + b to c |
| += | Add and assign | c += a is equivalent to c = c + a |
| -= | Subtract and assign | c -= a is equivalent to c = c - a |
| *= | Multiply and assign | c *= a is equivalent to c = c * a |
| /= | Divide and assign | c /= a is equivalent to c = c / a |
| %= | Modulus and assign | c %= a is equivalent to c = c % a |
| **= | Exponent and assign | c **= a is equivalent to c = c ** a |
| //= | Floor divide and assign | c //= a is equivalent to c = c // a |
| := | Walrus Operator. The main purpose of this operator is to assign and return the assigned value within an expression. **New operator in Python 3.8**. | In this example, the assignment expression avoids calling len() twice: if (n := len(a)) > 10: print(f"List is too long ({n} elements, expected 5:
print(n)
# Using walrus operator
if (n := 10) > 5:
print(n)
* `if (n := 10) > 5:`: This is the syntax using the walrus operator (`:=`). The walrus operator performs an assignment operation within an expression.
* `(n := 10)`: Assigns the value 10 to the variable `n` and returns this assignment result.
* `> 5`: Checks if the assigned `n` is greater than 5. If the condition is true, the following code block is executed.
* `print(n)`: If the condition is true, prints the value of variable `n` (which is 10).
**Advantages of the Walrus Operator:**
* The walrus operator (`:=`) allows assignment within an expression, which can reduce code duplication and improve code readability and conciseness.
* In the example above, the traditional way requires a separate line to assign `n`, and then a condition check in the `if` statement. The walrus operator syntax allows assignment and condition checking directly within the `if` statement.
* * *
## Python Bitwise Operators
Bitwise operators treat numbers as binary and perform calculations. The bitwise operations in Python are as follows:
In the table below, variable a is 60 and b is 13. Their binary formats are as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
| Operator | Description | Example |
| --- | --- | --- |
| & | Bitwise AND operator: If both corresponding bits of the two values are 1, the result bit is 1; otherwise, it is 0. | (a & b) outputs 12, binary explanation: 0000 1100 |
| | | Bitwise OR operator: If either of the corresponding bits is 1, the result bit is 1. | (a | b) outputs 61, binary explanation: 0011 1101 |
| ^ | Bitwise XOR operator: If the corresponding bits are different, the result is 1. | (a ^ b) outputs 49, binary explanation: 0011 0001 |
| ~ | Bitwise NOT operator: Inverts each bit of the data, i.e., changes 1 to 0 and 0 to 1. ~x is equivalent to -x-1. | (~a) outputs -61, binary explanation: 1100 0011, in two's complement form for a signed binary number. |
| << | Left shift operator: Shifts all bits of the operand to the left by the number of bits specified by the number on the right of "<<", discarding high bits and filling low bits with 0. | a <> | Right shift operator: Shifts all bits of the operand to the right by the number of bits specified by the number on the right of ">>". | a >> 2 outputs 15, binary explanation: 0000 1111 |
The following examples demonstrate the operations of all Python bitwise operators:
## Example (Python 3.0+)
```python
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0
c = a & b # 12 = 0000 1100
print("1 - Value of c: ", c)
c = a | b # 61 = 0011 1101
print("2 - Value of c: ", c)
c = a ^ b # 49 = 0011 0001
print("3 - Value of c: ", c)
c = ~a # -61 = 1100 0011
print("4 - Value of c: ", c)
c = a <> 2 # 15 = 0000 1111
print("6 - Value of c: ", c)
The output of the above example:
1 - Value of c: 12
2 - Value of c: 61
3 - Value of c: 49
4 - Value of c: -61
5 - Value of c: 240
6 - Value of c: 15
* * *
## Python Logical Operators
Python supports logical operators. The following assumes variable a is 10 and b is 20:
| Operator | Logical Expression | Description | Example |
| --- | --- | --- | --- |
| and | x and y | Boolean AND - If x is False, x and y returns the value of x; otherwise, it returns the evaluated value of y. | (a and b) returns 20. |
| or | x or y | Boolean OR - If x is True, it returns the value of x; otherwise, it returns the evaluated value of y. | (a or b) returns 10. |
| not | not x | Boolean NOT - If x is True, returns False. If x is False, returns True. | not(a and b) returns False |
The output of the above example:
## Example (Python 3.0+)
```python
a = 10
b = 20
if (a and b):
print("1 - Both variables a and b are true")
else:
print("1 - Either variable a or b is not true")
if (a or b):
print("2 - Both variables a and b are true, or one of them is true")
else:
print("2 - Neither variable a nor b is true")
a = 0
if (a and b):
print("3 - Both variables a and b are true")
else:
print("3 - Either variable a or b is not true")
if (a or b):
print("4 - Both variables a and b are true, or one of them is true")
else:
print("4 - Neither variable a nor b is true")
if not(a and b):
print("5 - Both variables a and b are false, or one of them is false")
else:
print("5 - Both variables a and b are true")
The output of the above example:
1 - Both variables a and b are true
2 - Both variables a and b are true, or one of them is true
3 - Either variable a or b is not true
4 - Both variables a and b are true, or one of them is true
5 - Both variables a and b are false, or one of them is false
* * *
## Python Membership Operators
In addition to the above operators, Python also supports membership operators, which test whether a sequence (such as a string, list, or tuple) contains a value.
| Operator | Description | Example |
| --- | --- | --- |
| in | Returns True if the value is found in the specified sequence, otherwise returns False. | x in y, returns True if x is in the sequence y. |
| not in | Returns True if the value is not found in the specified sequence, otherwise returns False. | x not in y, returns True if x is not in the sequence y. |
The following examples demonstrate the operations of all Python membership operators:
## Example (Python 3.0+)
```python
a = 10
b = 20
list = [1, 2, 3, 4, 5]
if (a in list):
print("1 - Variable a is in the given list")
else:
print("1 - Variable a is not in the given list")
if (b not in list):
print("2 - Variable b is not in the given list")
else:
print("2 - Variable b is in the given list")
a = 2
if (a in list):
print("3 - Variable a is in the given list")
else:
print("3 - Variable a is not in the given list")
The output of the above example:
1 - Variable a is not in the given list
2 - Variable b is not in the given list
3 - Variable a is in the given list
* * *
## Python Identity Operators
Identity operators are used to compare the memory locations of two objects.
| Operator | Description | Example |
| --- | --- | --- |
| is | is checks if two identifiers refer to the same object. | **x is y**, similar to **id(x) == id(y)**, returns True if they refer to the same object, otherwise returns False. |
| is not | is not checks if two identifiers refer to different objects. | **x is not y**, similar to **id(x) != id(y)**. Returns True if they do not refer to the same object, otherwise returns False. |
**Note:** The [id()](#) function is used to get the memory address of an object.
The following examples demonstrate the operations of all Python identity operators:
## Example (Python 3.0+)
```python
a = 20
b = 20
if (a is b):
print("1 - a and b have the same identity")
else:
print("1 - a and b do not have the same identity")
if (id(a) == id(b)):
print("2 - a and b have the same identity")
else:
print("2 - a and b do not have the same identity")
b = 30
if (a is b):
print("3 - a and b have the same identity")
else:
print("3 - a and b do not have the same identity")
if (a is not b):
print("4 - a and b do not have the same identity")
else:
print("4 - a and b have the same identity")
The output of the above example:
1 - a and b have the same identity
2 - a and b have the same identity
3 - a and b do not have the same identity
4 - a and b do not have the same identity
> Difference between `is` and `==`:
>
> `is` is used to check if two variables refer to the same object, while `==` is used to check if the values of the referenced variables are equal.
>
> ```python
> >>> a = [1, 2, 3]
> >>> b = a
> >>> b is a
> True
> >>> b == a
> True
> >>> b = a[:]
> >>> b is a
> False
> >>> b == a
> True
> ```
* * *
## Python Operator Precedence
The following table lists all operators from highest to lowest precedence. Operators in the same cell have the same precedence. All operators are binary unless otherwise noted. Operators in the same cell are grouped from left to right (except for exponentiation, which is grouped from right to left):
| Operator | Description |
| --- | --- |
| `(expressions...)`, `[expressions...]`, `{key: value...}`, `{expressions...}` | Parenthesized expressions |
| `x`, `x[index:index]`, `x(arguments...)`, `x.attribute` | Subscription, slicing, call, attribute reference |
| await x | Await expression |
| `**` | Exponentiation (power) |
| `+x`, `-x`, `~x` | Positive, negative, bitwise NOT |
| `*`, `@`, `/`, `//`, `%` | Multiplication, matrix multiplication, division, floor division, modulus |
| `+`, `-` | Addition and subtraction |
| `<>` | Bitwise shifts |
| `&` | Bitwise AND |
| `^` | Bitwise XOR |
| `|` | Bitwise OR |
| `in, not in, is, is not, <, , >=, !=, ==` | Comparisons, including membership tests and identity tests |
| `not x` | Boolean NOT |
| `and` | Boolean AND |
| `or` | Boolean OR |
| `if -- else` | Conditional expression |
| `lambda` | Lambda expression |
| `:=` | Assignment expression |
The following examples demonstrate the operations of all Python operator precedence:
## Example (Python 3.0+)
```python
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d
print("(a + b) * c / d evaluation result is: ", e)
e = ((a + b) * c) / d
print("((a + b) * c) / d evaluation result is: ", e)
e = (a + b) * (c / d)
print("(a + b) * (c / d) evaluation result is: ", e)
e = a + (b * c) / d
print("a + (b * c) / d evaluation result is: ", e)
The output of the above example:
(a + b) * c / d evaluation result is: 90.0
((a + b) * c) / d evaluation result is: 90.0
(a + b) * (c / d) evaluation result is: 90.0
a + (b * c) / d evaluation result is: 50.0
`and` has higher precedence:
## Example
```python
x = True
y = False
z = False
print("Case 1: Default precedence (and is evaluated first)")
if x or y and z:
print("yes")
else:
print("no")
print("nCase 2: Forced precedence change (or is evaluated first)")
if (x or y) and z:
print("yes")
else:
print("no")
In the above example, `y and z` is evaluated first and returns False, then `x or False` returns True. The output is:
Case 1: Default precedence (and is evaluated first)
yes
Case 2: Forced precedence change (or is evaluated first)
no
> **Note:** Python3 no longer supports the `` operator. You can use `!=` instead. If you must use this comparison operator, you can use the following method:
>
> ```python
> >>> from __future__ import barry_as_FLUFL
> >>> 1 2
> True
> ```
* * *
YouTip