Python Operators & ExpressionsGet Certified
What Are Operators and Expressions?
An operator is a symbol or a keyword that tells Python to perform an operation on one or more values. The values the operator works on are called operands. In 7 + 3, the plus sign is the operator and 7 and 3 are the operands.
An expression is any combination of values, variables, operators, and function calls that Python can evaluate to a single value. 7 + 3, price * quantity, and age >= 18 and has_id are all expressions. Every expression produces a result, and you can store that result in a variable, print it, or use it inside a larger expression.
- Arithmetic operators:
+ - * / // % **perform calculations. - Comparison operators:
== != < > <= >=compare values and returnTrueorFalse. - Logical operators:
and,or, andnotcombine conditions. - Assignment operators:
=and shortcuts such as+=store results in variables. - Membership and identity operators:
in,not in,is, andis not. - Bitwise operators:
& | ^ ~ << >>work on the binary digits of integers.
Arithmetic Operators
Arithmetic operators work on numbers. Most behave as you would expect from mathematics, but Python has three division-related operators that deserve attention:
/is true division. It always returns a float, even for6 / 3, which gives2.0.//is floor division. It divides and rounds the result down to the nearest whole number.%is the modulo operator. It returns the remainder of a division, and its result has the same sign as the divisor.**raises the left operand to the power of the right operand.
Floor division and modulo always work together: a == (a // b) * b + a % b. This explains why -17 // 5 is -4 and not -3. Rounding down moves toward negative infinity.
Try It: The Seven Arithmetic Operators
Click Test My Code and check each result by hand. Then change a and b and run it again.
a = 17
b = 5
print(a + b, a - b, a * b)
print(a / b, a // b, a % b)
print(a ** 2)
print(-17 // 5, -17 % 5)a = 17 stores the integer 17.b = 5 stores the integer 5.22, 12, and 85. The output is 22 12 85.17 / 5 is 3.4. 17 // 5 is 3, because the result is rounded down. 17 % 5 is 2, the remainder. The output is 3.4 3 2.a ** 2 means 17 squared, so the output is 289.-17 // 5 is -3.4 rounded down, which gives -4. The matching remainder is -17 % 5 = 3, because (-4) * 5 + 3 = -17. The output is -4 3.Operator Precedence
When an expression contains several operators, Python does not simply work from left to right. It follows rules of precedence, which decide which operator is applied first, just like the order of operations in mathematics. Operators with the same precedence are usually evaluated from left to right. The exception is **, which is evaluated from right to left. From highest to lowest precedence, the main groups are:
- Parentheses
( ). - Exponent
**. - Unary
+x,-x, and~x. - Multiplication, division, floor division, modulo
* / // %. - Addition and subtraction
+ -. - Shifts
<< >>, then bitwise&,^,|. - Comparisons, membership, and identity
== != < > in isand so on. - Logical
not, thenand, thenor.
When in doubt, add parentheses. They cost nothing and make the intention clear to the reader.
Try It: Precedence in Action
Click Test My Code. Predict each of the six results first, especially the third and fourth lines.
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)
print(-2 ** 2)
print(10 - 4 - 3)
print(100 / 10 * 2)3 * 4 first, then adds 2. The output is 14.2 + 3 to be calculated first, so the output is 20.2 ** 3 ** 2 is read as 2 ** (3 ** 2), which is 2 ** 9. The output is 512.-2 ** 2 is read as -(2 ** 2), so the output is -4, not 4. Write (-2) ** 2 to get 4.(10 - 4) - 3. The output is 3.100 / 10 is 10.0, and then multiplying by 2 gives 20.0. The result is a float because / always returns one.Comparison Operators
Comparison operators compare two values and return a Boolean. The six operators are == (equal), != (not equal), <, >, <=, and >=. They work on numbers, and also on strings, which are compared character by character using their Unicode order. Python also allows chained comparisons such as 1 < x < 10, which means 1 < x and x < 10.
Try It: Comparing Values
Click Test My Code. The last line compares floats, so read the explanation to see why the answer is surprising.
x = 7
print(x == 7, x != 7, x > 5, x <= 6)
print(1 < x < 10)
print("apple" < "banana", "a" == "A")
print(0.1 + 0.2 == 0.3)x = 7 stores the integer 7.True, False, True, and False, because 7 equals 7, 7 is not different from 7, 7 is greater than 5, and 7 is not less than or equal to 6.1 < x < 10 checks that x lies between 1 and 10. The output is True."apple" < "banana" is True because a comes before b. "a" == "A" is False because uppercase and lowercase letters are different characters. The output is True False.0.1 + 0.2 is stored as 0.30000000000000004, so it is not exactly equal to 0.3. The output is False. Use round() or math.isclose() to compare floats.Logical Operators
Logical operators combine two or more Boolean conditions to create complex decision-making expressions. They allow Python to check whether multiple conditions are true or false using operators such as `and`, `or`, and `not`.
and: true only when both sides are true.or: true when at least one side is true.not: reverses a Boolean value.- Short-circuiting:
andandorstop as soon as the result is known, so the right side is not always evaluated. - They return operands:
x and yreturnsxifxis falsy, otherwisey.x or yreturnsxifxis truthy, otherwisey. This is whyoris often used to supply a default value.
Try It: and, or, not
Click Test My Code. The last three lines show that and and or return one of their operands, not just True or False.
and, or, and not. It then shows how or picks a default value and how and returns one of its operands.age = 25
has_id = True
print(age >= 18 and has_id)
print(age < 18 or has_id)
print(not has_id)
print(0 or "default")
print("hello" and "world")
print(repr("" and "never"))age refers to 25.has_id refers to True.age >= 18 and has_id are true, so the output is True.age < 18 is false but has_id is true. One true side is enough for or, so the output is True.not reverses True, so the output is False.0 is falsy, so or returns its right operand. The output is default."hello" is truthy, so and moves on and returns the right operand. The output is world.and stops there and returns it, and the right operand is never evaluated. repr() shows the empty string as '', so the output is ''.Assignment and Augmented Assignment
The basic assignment operator = stores a value in a variable. Augmented assignment operators combine an operation and an assignment in one step. For example, score += 5 means score = score + 5. Every arithmetic operator has an augmented form: +=, -=, *=, /=, //=, %=, and **=. The variable must already exist, because Python reads its current value before it calculates the new one.
Try It: Shortcut Assignments
Click Test My Code. The variable score is changed five times before it is printed. Work through the steps on paper to check the final value.
+= to add 1 to a counter, which is the most common use of this operator.score = 10
score += 5
score *= 2
score -= 4
score //= 3
score **= 2
print(score)
count = 0
count += 1
print("count =", count)score = 10 creates the variable.score += 5 is the same as score = score + 5, so score becomes 15.score *= 2 makes score equal to 30.score -= 4 makes score equal to 26.score //= 3 divides 26 by 3 and rounds down, so score becomes 8.score **= 2 squares the value, so score becomes 64.64.count = 0 creates a counter that starts at zero.count += 1 adds one to the counter. This pattern appears in almost every loop.count = 1.Membership and Identity Operators
The membership operators in and not in test whether a value is present in a sequence or collection. They work with lists, tuples, sets, dictionaries (which check the keys), and strings (which check for a substring).
The identity operators is and is not test whether two names refer to the very same object in memory. This is different from ==, which tests whether two values are equal. Use is mainly for comparing with None, as in x is None.
Try It: in, not in, is and ==
Click Test My Code and notice that a == b is true while a is b is false, because a and b are two separate lists with the same contents.
== and is. The last line tests against None.fruits = ["apple", "banana", "cherry"]
print("banana" in fruits, "grape" not in fruits)
print("th" in "Python")
a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)
print(None is None, a is not None)fruits refers to a list of three strings."banana" in fruits is True, and "grape" not in fruits is also True. The output is True True.in checks for a substring. The letters th appear in Python, so the output is True.a refers to a new list [1, 2].b refers to a different list object that happens to hold the same items.c = a does not create a copy. It gives the same list a second name.a == b is True because the contents are equal. a is b is False because they are different objects. a is c is True because both names refer to the same object. The output is True False True.None is None is True, and the list a is not None, so a is not None is also True. The output is True True.Operators on Strings and Lists, and the Conditional Expression
Some operators have a different meaning for non-numeric types. The + operator concatenates (joins) strings and lists, and the * operator repeats them. Python also offers a one-line conditional expression (sometimes called the ternary operator) with the form value_if_true if condition else value_if_false.
Try It: Joining, Repeating and Choosing
Click Test My Code. Change n to an odd number and run it again.
+ and *. It then uses a conditional expression and the modulo operator to print whether a number is even or odd.print("ab" + "cd", "ab" * 3)
print([1, 2] + [3], [0] * 4)
n = 8
print("even" if n % 2 == 0 else "odd")"ab" + "cd" joins the strings into abcd, and "ab" * 3 repeats the string three times. The output is abcd ababab.[1, 2] + [3] builds the list [1, 2, 3], and [0] * 4 builds [0, 0, 0, 0]. The output is [1, 2, 3] [0, 0, 0, 0].n = 8 stores the integer 8.n % 2 == 0 is true when the remainder after dividing by 2 is zero, which means that n is even. The expression then gives "even". For an odd number it would give "odd". The output is even.Bitwise Operators
Bitwise operators work on the individual binary digits (bits) of integers. They are less common in everyday programs, but they appear in low-level code, flags, and permissions. & (AND) keeps bits that are 1 in both numbers, | (OR) keeps bits that are 1 in either, ^ (XOR) keeps bits that differ, << shifts bits to the left, which doubles the number for each step, and >> shifts bits to the right, which halves it. The built-in bin() function shows the binary form of a number.
Try It: Working with Bits
Click Test My Code. The explanation shows each number in binary so you can follow the result.
a = 12
b = 10
print(a & b, a | b, a ^ b)
print(a << 1, a >> 2)
print(bin(a), bin(b))12 is 1100 in binary.10 is 1010 in binary.1100 and 1010 bit by bit: AND gives 1000 (8), OR gives 1110 (14), and XOR gives 0110 (6). The output is 8 14 6.12 << 1 moves the bits one place left, which gives 24. 12 >> 2 moves them two places right, which gives 3. The output is 24 3.bin() returns the binary text, with the prefix 0b. The output is 0b1100 0b1010.Putting It Together: A Calculator
Operators become useful when they work on values supplied by the user. The following program reads two numbers and shows several results at once. Remember that input() returns text, so the values are converted to floats first.
Try It: A Small Calculator
The Program Input box is already filled with 17 on the first line and 5 on the second line. Click Run Code straight away, then try other numbers. If you enter 0 as the second number, Python raises a ZeroDivisionError.
a = float(input("First number: "))
b = float(input("Second number: "))
print(f"{a} + {b} = {a + b}")
print(f"{a} / {b} = {a / b:.2f}")
print(f"{a} // {b} = {a // b}")
print(f"{a} % {b} = {a % b}")
print("Is the first larger?", a > b)input() reads the first line of the Program Input box, and float() converts it to 17.0.5.0.a + b inside the braces. The output is 17.0 + 5.0 = 22.0.:.2f shows the quotient with two decimals. The output is 17.0 / 5.0 = 3.40.17.0 // 5.0 = 3.0.2.0. The output is 17.0 % 5.0 = 2.0.a > b is True, so the output is Is the first larger? True.Tip: If a long expression is hard to read, split it into several short lines with well-named variables, or add parentheses. Clear code is better than clever code.
Common Mistakes with Operators
- Using
=instead of==:=assigns a value and==compares two values. Writingif x = 5:is aSyntaxError. - Expecting
/to give an integer:10 / 2is5.0. Use//for a whole-number result. - Misreading
-2 ** 2: it equals-4, because the exponent is applied before the minus sign. - Using
isto compare values:ischecks identity, not equality. Use==for numbers, strings, and lists, and keepisforNone. - Mixing up
andwith&:andcombines conditions logically, while&works on bits. Useand,or, andnotin conditions. - Comparing floats with
==:0.1 + 0.2 == 0.3isFalse. Compare withround()ormath.isclose(). - Dividing by zero:
5 / 0,5 // 0, and5 % 0raise aZeroDivisionError. Check the divisor first.
Key Takeaways
- An operator performs an operation on operands, and an expression is any combination that Python can evaluate to a single value.
/always returns a float,//rounds down,%gives the remainder, and**raises to a power.- Precedence decides the order of evaluation. Use parentheses whenever the order is not obvious.
- Comparison operators return Booleans, and they can be chained, as in
1 < x < 10. andandorshort-circuit and return one of their operands, andnotreverses a Boolean.- Augmented assignment, such as
+=, updates a variable in one step. intests membership,istests identity, and==tests equality.
Frequently Asked Questions
What are operators in Python?
Operators are symbols or keywords that perform an operation on values, which are called operands. Python has arithmetic, comparison, logical, assignment, bitwise, membership, and identity operators. For example, in 7 + 3 the plus sign is the operator and 7 and 3 are the operands.
What is the difference between / and // in Python?
The / operator is true division and always returns a float, so 7 / 2 gives 3.5. The // operator is floor division and rounds the result down to the nearest whole number, so 7 // 2 gives 3 and -7 // 2 gives -4.
What does the % operator do in Python?
The % operator is the modulo operator. It returns the remainder after division, so 17 % 5 gives 2. It is often used to test whether a number is even, with n % 2 == 0, or to wrap a value around a limit.
What is the difference between == and is in Python?
The == operator checks whether two values are equal, while the is operator checks whether two names refer to the same object in memory. Two separate lists with the same items are equal but are not identical. Use is mainly to compare with None.
How does operator precedence work in Python?
Precedence decides which operator is applied first. Parentheses come first, then the exponent, then unary signs, then multiplication and division, then addition and subtraction, then comparisons, and finally not, and, and or. Operators of equal precedence run from left to right, except for the exponent, which runs from right to left.
What is short-circuit evaluation in Python?
The and and or operators stop evaluating as soon as the result is known. In x and y, if x is falsy Python returns x without evaluating y. In x or y, if x is truthy Python returns x without evaluating y. This also means that they return one of their operands, not necessarily True or False.
What is the difference between and and & in Python?
The and keyword is a logical operator that combines conditions and short-circuits. The & symbol is a bitwise operator that works on the binary digits of integers. Use and, or, and not when writing conditions in if statements.
What does += mean in Python?
The += operator is an augmented assignment. The statement x += 5 means x = x + 5, so it adds 5 to the current value of x. Python has the same shortcut for the other arithmetic operators, such as -=, *=, /=, //=, %=, and **=.