top of page

Python Operators: A Beginner’s Reference Guide

Updated: Jun 24

Introduction to Python Operators

In programming, an operator is a symbol (or a combination of symbols) that tells the interpreter to perform a specific operation on one or more pieces of data (called operands). In Python, operators are used as shortcuts to manipulate data, perform calculations, compare values, assign values to variables, and more. For example, the plus sign (+) is an arithmetic operator that adds two numbers, while the keyword `and` is a logical operator that combines two Boolean conditions.


Python provides a variety of built-in operators, which can be categorized as follows:


  1. Assignment Operators: assign or reassign values to variables, sometimes combining assignment with another operation.


  1. Arithmetic Operators: perform mathematical calculations on numeric values (e.g., addition, subtraction).


  1. Comparison Operators: compare two values and evaluate to a Boolean result (True or False).


  1. Logical (Boolean) Operators: combine multiple conditions or Boolean values into a single logical expression.


  1. Bitwise Operators: perform operations on numbers at the binary (bit) level.


  1. Membership Operators: test whether a value is a member of a sequence or collection (like a list or string).


  1. Identity Operators: check whether two references point to the exact same object in memory.


Each category of operator serves a different purpose. In the sections below, we’ll explain each type of operator, list the operators in that category with their behavior, and show simple code examples demonstrating how they work.



Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations. These are the basic math symbols you likely already know. In Python, arithmetic operators work on integers, floating-point numbers, and other numeric types. The standard arithmetic operators are:


  1. Addition (+): Adds two numbers. For example, 5 + 3 evaluates to 8 (the sum of 5 and 3).


  1. Subtraction (-): Subtracts the right operand from the left operand. For example, 5 - 3 evaluates to 2 (5 minus 3). The `-` operator can also be unary (with one operand) to denote a negative number (e.g., -7).


  1. Multiplication (*): Multiplies two numbers. For example, 5 * 3 evaluates to 15 (the product of 5 and 3).


  1. Division (/): Divides the left operand by the right operand. This always produces a floating-point result in Python 3, even if the numbers divide evenly. For example, 10 / 5 results in 2.0 (a float) rather than 2.


  1. Floor Division (//): Divides the left operand by the right operand and floors (rounds down) the result to the nearest whole number. It returns an integer quotient. For example, 17 // 5 evaluates to 3 (since 17/5 is 3.4, floor division gives 3). Floor division is sometimes called integer division.


  1. Modulo (%): Returns the remainder of dividing the left operand by the right operand. For example, 17 % 5 evaluates to 2 (since 17 divided by 5 leaves a remainder of 2).


  2. Exponentiation (**): Raises the left operand to the power of the right operand. For example, 2 ** 3 evaluates to 8 (since 2 to the power of 3 is 8). This operator is evaluated before other arithmetic operators due to its high precedence, as we’ll discuss later.


Assignment Operators

Assignment operators are used to assign values to variables. The simplest assignment operator is the single equals sign =, which takes the value on the right and assigns it to the variable on the left. In addition, Python provides augmented assignment operators that combine another operation with assignment, which offers a shorthand for updating variables (x += 3 is a shortcut for x = x + 3). The main assignment operators in Python include:


  1. Simple Assignment (=): Assigns the value of the right-hand side to the left-hand side variable. For example, x = 5 means the variable x now holds the value 5.


  1. Add and Assign (+=): Adds the right-hand side value to the left-hand side variable and assigns the result back to the left-hand side. For example, x += 3 is equivalent to x = x + 3. If x were 5, it would become 8 after this operation.


  1. Subtract and Assign (-=): Subtracts the right-hand side value from the variable and assigns the result to the variable (i.e., x -= 3 is x = x - 3).


  1. Multiply and Assign (*=): Multiplies the variable by the right-hand side value and assigns the result (i.e., x = 3 means x = x * 3).


  1. Divide and Assign (/=): Divides the variable by the right-hand side value and assigns the result (i.e., x /= 3 means x = x / 3). The result will be a float if using standard division.


  1. Floor-Divide and Assign (//=): Performs floor division on the variable by the right-hand value and assigns the integer result (i.e., x //= 3 means x = x // 3).


  1. Modulo and assign (%=): Takes the remainder of the variable divided by the right-hand value and assigns it back to the variable (x %= 3 means x = x % 3).


  1. Exponentiate and assign (**=): Raises the variable to the power of the right-hand value and assigns the result (x = 3 means x = x ** 3).


Using augmented assignment operators can make code more concise. It’s important to note that the variable on the left must already have a value before you use an augmented assignment; otherwise, you’ll get a NameError (since Python wouldn’t know the original value to combine with).


Comparison Operators

Comparison operators (also known as relational operators) are used to compare two values and determine the relationship between them. A comparison expression yields a Boolean value: True if the comparison is satisfied, or False otherwise. These operators are typically used in conditional statements (like if statements) or anywhere you need to evaluate a condition. Python’s comparison operators include:


  1. Equal to (==): Returns True if the left and right operands are equal in value, and False otherwise. For example, 5 == 5 is True, but 5 == 3 is False.


  1. Not equal to (!=): Returns True if the two operands are not equal in value, and False if they are equal. For example, 5 != 3 is True (because 5 is not equal to 3).


  1. Greater than (>): Returns True if the left operand is strictly greater than the right operand. For example, 7 > 4 is True. If not, returns False (e.g., 4 > 7 is False).


  1. Less than (<): Returns True if the left operand is strictly less than the right operand. For example, 4 < 7 is True.


  1. Greater than or equal to (>=): Returns True if the left operand is greater than or equal to the right operand. For example, 5 >= 5 is True (equal counts as meeting the condition), and 7 >= 5 is True as well. It returns False only if the left side is strictly smaller.


  1. Less than or equal to (<=): Returns True if the left operand is less than or equal to the right operand. For example, 5 <= 5 is True, 3 <= 5 is True. It’s False only if the left side is strictly greater.


All comparison operators are binary (take two operands) and they yield a Boolean result (True or False). Comparisons can be made between numbers, and also between other types that are comparable (e.g., strings can be compared lexicographically). However, comparing incompatible types (like a number and a string with < or >) is not allowed and will result in a TypeError in Python.


Logical (Boolean) Operators

Logical operators (also known as Boolean operators) are used to combine conditional statements or Boolean values. They allow you to form more complex conditions by and-ing or or-ing simpler conditions, as well as negating conditions with not. In Python, the logical operators are the English words and, or, and not (instead of symbols like && or || in some other languages). These operators work on Boolean values (True or False), and the result is also a Boolean. The logical operators are:


  1. and: Returns True only if both operands (conditions) are true. If either operand is false, the result is False. For example, (x > 0 and x < 10) is true only if both conditions are true (i.e., x is between 0 and 10).


  1. or: Returns True if at least one of the operands is true. It returns False only when both operands are false. For example, (x < 5 or y < 5) is true if either x is less than 5 or y is less than 5 (or both).


  1. not: This is a unary operator (takes only one operand) that negates a Boolean value. It returns True if the operand is false, and False if the operand is true. For example, not(True) evaluates to False, and not (x > 5) is true if x > 5 is false (meaning x is not greater than 5).


These logical operators enable you to build complex logical expressions. Python also uses short-circuit evaluation for and and or – meaning it stops evaluating as soon as the result is determined (for instance, if the first condition in an and is false, Python won't evaluate the second condition, because the whole expression will already be false). This can be useful for efficiency or to avoid errors (like checking an object is not None and then accessing its attribute in the same expression).


Operator Precedence and Order of Evaluation

When an expression involves multiple operators, operator precedence determines the order in which those operations are evaluated. In Python (as in mathematics), certain operations are performed before others by default. For example, multiplication has a higher precedence than addition, which means in an expression like 2 + 5 3, the multiplication is done first. Indeed, 2 + 5 3 will be interpreted as 2 + (5 3) and evaluate to 17, not (2 + 5) 3 (which would be 21). Python’s operator precedence follows well-known rules:


  • Parentheses have the highest precedence. Any expression inside ( ) is evaluated first. You can use parentheses to override default precedence or to make an expression clearer.


  • Exponentiation (**) is evaluated next, before other arithmetic operators. Notably, exponentiation is right-associative, which means in an expression like 2 3 2, Python evaluates it as 2 (3 2) (resulting in 2 ** 9 = 512).


  • Unary plus, minus, and bitwise NOT, the unary operators (like the negative sign in -5 or ~x) come after exponentiation but before multiplication.


  • Multiplication, Division, Floor Division, Modulo (*, /, //, %) are evaluated next, before addition and subtraction. So in 5 + 3 * 4, the result is 5 + 12 = 17 because the 3 * 4 is done first.


  • Addition and Subtraction (+, -) – come after the above operations.


  • Bitwise shifts (<<, >>), bitwise AND (&), XOR (^), OR (|) – these come in increasing order of precedence after the arithmetic operations (shifts first, then AND, then XOR, then OR).


  • Comparisons (==, !=, <, >, <=, >=), Identity (is, is not), Membership (in, not in) – are evaluated after all the aforementioned arithmetic and bitwise operators. Note that all comparison-like operators have the same precedence and also support chaining (e.g., a < b < c).


  • Logical NOT (not) – comes next.


  • Logical AND (and) – comes after not.


  • Logical OR (or) – has the lowest precedence of the logical operators, evaluated last among them.


In summary, arithmetic operators have higher precedence than comparison operators, which in turn have higher precedence than logical operators. This means an expression like x < 5 or x + 2 > 10 will evaluate the arithmetic addition first, then the comparisons, and finally the OR.


If two operators have the same precedence, the expression is generally evaluated left-to-right (i.e., left-associative). For example, addition and subtraction have the same precedence, so 5 - 2 + 3 is evaluated left-to-right as (5 - 2) + 3. (One exception is exponentiation **, which, as noted, is right-associative.)


You do not need to memorize the entire precedence table – when in doubt, or to make code more readable, you can always use parentheses to group operations explicitly. Using parentheses can clarify the intended order of evaluation and ensure your expressions are evaluated correctly. For example, even though and has lower precedence than <, some programmers might write an expression like (a < 10) and (b > 30) for clarity. This doesn’t change the result, but it can make the code easier to understand.

 
 
 

Kommentarer


bottom of page