Academic Block

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 return True or False.
  • Logical operators: and, or, and not combine conditions.
  • Assignment operators: = and shortcuts such as += store results in variables.
  • Membership and identity operators: in, not in, is, and is 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 for 6 / 3, which gives 2.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.

What this code does: It applies addition, subtraction, multiplication, true division, floor division, modulo, and exponentiation to two integers. The last line repeats floor division and modulo with a negative number to show how rounding down works.
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)

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 is and so on.
  • Logical not, then and, then or.

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.

What this code does: It shows that multiplication happens before addition, that parentheses change the order, that the exponent operator is evaluated right to left, and that the exponent binds more tightly than the unary minus.
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)
print(-2 ** 2)
print(10 - 4 - 3)
print(100 / 10 * 2)

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.

What this code does: It compares a number with several other numbers, uses a chained comparison, compares strings alphabetically and checks that uppercase and lowercase letters differ, and finally compares two floating-point sums.
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)

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: and and or stop as soon as the result is known, so the right side is not always evaluated.
  • They return operands: x and y returns x if x is falsy, otherwise y. x or y returns x if x is truthy, otherwise y. This is why or is 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.

What this code does: It combines two conditions about an age and an ID with 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"))

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.

What this code does: It starts a score at 10 and applies five augmented assignments in a row, then prints the result. It also uses += 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)

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.

What this code does: It tests membership in a list and in a string. It then creates two equal lists and a third name for the first list, and compares them with == 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)

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.

What this code does: It joins and repeats strings and lists with + 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")

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.

What this code does: It applies the bitwise AND, OR, and XOR operators to the numbers 12 and 10, shifts 12 left and right, and prints both numbers in binary.
a = 12
b = 10
print(a & b, a | b, a ^ b)
print(a << 1, a >> 2)
print(bin(a), bin(b))

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.

What this code does: It reads two numbers as floats and prints their sum, their quotient to two decimal places, their floor division, and their remainder. The last line uses a comparison operator to check which number is larger.
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)
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. Writing if x = 5: is a SyntaxError.
  • Expecting / to give an integer: 10 / 2 is 5.0. Use // for a whole-number result.
  • Misreading -2 ** 2: it equals -4, because the exponent is applied before the minus sign.
  • Using is to compare values: is checks identity, not equality. Use == for numbers, strings, and lists, and keep is for None.
  • Mixing up and with &: and combines conditions logically, while & works on bits. Use and, or, and not in conditions.
  • Comparing floats with ==: 0.1 + 0.2 == 0.3 is False. Compare with round() or math.isclose().
  • Dividing by zero: 5 / 0, 5 // 0, and 5 % 0 raise a ZeroDivisionError. 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.
  • and and or short-circuit and return one of their operands, and not reverses a Boolean.
  • Augmented assignment, such as +=, updates a variable in one step.
  • in tests membership, is tests 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 **=.

Ready for the next step?Learn how to create, slice, and format text with strings.
Next: Strings & String Formatting →