Operators are used to perform various operations on variables and values. The standard arithmetic and assignment operators are the most familiar.
The following code snippet uses the assignment operator,
=, to set
my_variable to the value of
num2 with an arithmetic operator acting on them. For example, if
my_variable would be assigned a value of
num1 * num2.
my_variable = num1 operator num2
Python operators can be organized into the following groups:
- Arithmetic operators for performing traditional math evaluations.
- Assignment operators for assigning values to variables.
- Comparison operators for comparing two values.
- Logical operators for combining boolean values.
Python has the following arithmetic operators:
+, which returns the sum of two numbers.
-, which returns the difference of two numbers.
*, which returns the product of two numbers.
/, which returns the quotient of two numbers.
**, which returns the value of one number raised to the power of another.
%, which returns the remainder of one number divided by another.
- Floor division,
//, which returns the integer quotient of two numbers.
Python includes the following assignment operators:
=operator assigns the value on the left to the variable on the right.
+=operator updates a variable by incrementing its value and reassigning it.
-=operator updates a variable by decrementing its value and reassigning it.
*=operator updates a variable by multiplying its value and reassigning it.
/=operator updates a variable by dividing its value and reassigning it.
%=operator updates a variable by calculating its modulus against another value and reassigning it.
Python has the following comparison operators:
==, for returning
Trueif two values are equal.
- Not equal,
!=, for returning
Trueif two values are not equal.
- Less than,
<, for returning
Trueif left value less than right value.
- Less than or equal to,
<=, for returning
Trueif left value is less than or equal to right value.
- Greater than,
>, for returning
Trueif left value greater than right value.
- Greater than or equal to,
>=, for returning
Trueif left value greater than or equal to right value.
Python has the following logical operators:
Trueif both statements are
Trueif either statement is
Trueif its associated statement is
Order of Operations
Python evaluates an expression in order of precedence as follows:
- Items in parentheses, (
)), have the highest level of precedence, expressions within them are evaluated first.
- Exponentiation (
- Multiplication and division operators (
- Addition and subtraction (
- Comparison (
- Equality (
Note: Items at the same precedence are evaluated left to right. The exception to this is exponentiation, which evaluates right to left.