Operators
An operator is a symbol or keyword that tells Python to perform a specific operation on one or more values (also called operands). Operators allow you to perform tasks like adding numbers, comparing values, assigning results to variables, or evaluating logical conditions.
Types of operators
Section titled “Types of operators”In Python, just like in other languages, there are a variety of operator types which we will teach you below.
Arithmetic Operators
Section titled “Arithmetic Operators”These are the most basic operators and are used to perform mathematical operations like addition, subtraction, multiplication, or division. Python uses them to work with numbers directly.
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division (float result) |
// | Integer division |
% | Modulo (remainder) |
** | Power |
x = 12y = 24
print(x + y) # Result: 36print(x - y) # Result: -12print(x * y) # Result: 288print(x / y) # Result: 0.5print(x // y) # Result: 0print(x % y) # Result: 12
Comparison Operators
Section titled “Comparison Operators”These operators allow you to compare two values. The result of a comparison is always a boolean value: True if the condition is met, and False if not.
Operator | Description |
---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
print(5 == 5) # Result: Trueprint(5 != 3) # Result: Trueprint(7 > 3) # Result: Trueprint(2 < 4) # Result: Trueprint(6 >= 6) # Result: Trueprint(3 <= 5) # Result: True
Assignment Operators
Section titled “Assignment Operators”Assignment operators are symbols used in programming to assign a value to a variable. The most common assignment operator is the equals sign (=), but there are also compound assignment operators that combine an operation with assignment.
Operator | Description |
---|---|
= | Assignment |
+= | Addition and assignment |
-= | Subtraction and assignment |
*= | Multiplication and assignment |
/= | Division and assignment |
%= | Modulo and assignment |
//= | Integer division and assignment |
**= | Power and assignment |
print(x = 5) # Assigns the value 5 to xprint(x += 3) # x = x + 3print(x -= 2) # x = x - 2print(x *= 4) # x = x * 4print(x /= 2) # x = x / 2print(x %= 3) # x = x % 3print(x //= 2) # x = x // 2print(x **= 3) # x = x ** 3
Logical Operators
Section titled “Logical Operators”They are used to combine multiple conditions and get a boolean result. They are usually used in control structures like conditionals.
Operator | Description | Example | Result |
---|---|---|---|
and | True if both conditions are true | True and False | False |
or | True if at least one condition is true | True or False | True |
not | Inverts the value of the condition | not True | False |