Operators in Python
In Python, an operator is a symbol that represents a specific operation, such as addition or subtraction. Operators are used to perform mathematical or logical operations on variables or values.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on numeric data types. The following table shows the arithmetic operators in Python:
Operator | Description | Example | Result |
---|---|---|---|
+ | Addition | 3 + 5 | 8 |
- | Subtraction | 7 - 2 | 5 |
* | Multiplication | 4 * 3 | 12 |
/ | Division | 10 / 3 | 3.3333... |
// | Integer division | 10 // 3 | 3 |
% | Modulus | 10 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
Comparison Operators
Comparison operators are used to compare two values and return a Boolean value of
True
or
False
. The following table shows the comparison operators in Python:
Operator | Description | Example | Result |
---|---|---|---|
== | Equal to | 3 == 5 | False |
!= | Not equal to | 7 != 2 | True |
< | Less than | 4 < 3 | False |
> | Greater than | 10 > 3 | True |
<= | Less than or equal to | 3 <= 3 | True |
>= | Greater than or equal to | 10 >= 10 | True |
Logical Operators
Logical operators are used to combine multiple Boolean values and return a Boolean value of
True
or
False
. The following table shows the logical operators in Python:
Operator | Description | Example | Result |
---|---|---|---|
and | True if both operands are True | True and False | False |
or | True if at least one operand is True | True or False | True |
not | True if operand is False, and vice versa | not True | False |
Assignment Operators
Assignment operators are used to assign values to variables. The following table shows the assignment operators in Python:
Operator | Description | Example | Equivalent to |
---|---|---|---|
= | Assign value to variable | x = 5 | x = 5 |
+= | Add and assign | x += 3 | x = x + 3 |
-= | Subtract and assign | x -= 2 | x = x - 2 |
*= | Multiply and assign | x *= 4 | x = x * 4 |
/= | Divide and assign | x /= 2 | x = x / 2 |
//= | Integer divide and assign | x //= 3 | x = x // 3 |
%= | Modulus and assign | x %= 2 | x = x % 2 |
**= | Exponentiate and assign | x **= 3 | x = x ** 3 |
That's a brief overview of the different types of operators available in Python. Understanding operators is essential for writing effective Python code, and with practice, you will become more comfortable using them. Keep in mind that Python follows a specific order of operations when evaluating expressions. If you are unsure of the order of operations, you can use parentheses to explicitly specify the order in which expressions are evaluated. In addition to the built-in operators provided by Python, you can also define your own custom operators using Python's operator overloading feature. This allows you to define custom behavior for operators when used with objects of your own classes. I hope this helps you in understanding the different types of operators available in Python!