Basics

Operator in Python: Arithmetic, // and %, Comparison, and/or/not and round()

Updated: · Skillaria.Top

The / operator in Python always gives a float, // gives the integer part rounded down, % gives the remainder, and ** is exponentiation. The round(x, n) function rounds to n digits using banker's rounding: round(2.5) is 2, while round(3.5) is 4. math.ceil and math.floor round up and down to an integer, and abs gives the absolute value of a number.

Python operators are the symbols that turn values into new values: + adds, // divides with the integer part only, and combines conditions. Below you will find the full list of operators with examples, the difference between / and //, the logic of and, or and not, and the rounding functions: Python round, math.ceil, math.floor and abs. You can paste every example into the REPL and check it yourself.

List of Python operators

Operators fall into groups by purpose. You do not need to memorise the whole table: in real code you meet arithmetic, comparison and logical operators most often.

GroupOperatorsExample
Arithmetic+ - * / // % **7 // 2 → 3
Comparison== != < > <= >=3 < 5 → True
Logicaland or notnot True → False
Identityis, is notx is None
Membershipin, not in"c" in "coffee" → True
Assignment= += -= *= /= //= %= **=total += 250
Walrus:=if (n := len(s)) > 10:
Bitwise& | ^ ~ << >>5 & 3 → 1

Arithmetic operators

Addition, subtraction and multiplication work as you learned at school. If at least one operand is a float, the result is also a float: 2 + 1.0 gives 3.0. Integers in Python never overflow: 2 ** 100 is computed exactly, however many digits it has.

>>> 250 + 120
370
>>> 12.5 * 3
37.5
>>> 2 ** 10
1024
>>> 2 ** 0.5
1.4142135623730951

Power in Python: the ** operator

Exponentiation uses two asterisks, not ^: in Python the caret means bitwise "exclusive OR", so 2 ^ 3 returns 1, not 8. A fractional exponent gives a root: 9 ** 0.5 equals 3.0. There is also the function pow(x, y), which does the same, plus a third argument for the remainder: pow(2, 10, 1000) returns 24.

Mind the precedence: ** runs before unary minus, so -2 ** 2 equals -4. If you need the square of a negative number, use brackets: (-2) ** 2.

Division in Python: /, // and %

Python has two kinds of division, and this is the main source of surprises for beginners. Ordinary division / always returns a float, even when the division is exact. Integer division // discards the fractional part, and % returns the remainder.

>>> 7 / 2
3.5
>>> 8 / 2
4.0
>>> 7 // 2
3
>>> 7 % 2
1

Integer division // and remainder %: in practice

The pair // and % answers the questions "how many whole ones, and how much is left". In the course, the expense tracker stores money in cents to keep precision, and splits the sum into dollars and cents:

cents = 125050            # store money in cents
dollars = cents // 100    # 1250 — whole dollars
rest = cents % 100        # 50 — the remainder
print(dollars, rest)      # 1250 50

print(40 // 7, "weeks and", 40 % 7, "days")   # 5 weeks and 5 days

The built-in function divmod returns both results at once: divmod(125050, 100) gives the tuple (1250, 50). The remainder is also handy for checking evenness: n % 2 == 0 is true for even numbers.

Negative numbers: // rounds down

The // operator does not simply drop the fraction: it rounds down, towards minus infinity. For positive numbers there is no difference, but for negative ones there is. In Python the sign of the % remainder matches the sign of the divisor, so the equality a == (a // b) * b + a % b always holds.

>>> -7 // 2
-4
>>> -7 % 2
1
>>> int(-7 / 2)     # drop the fraction instead of rounding down
-3

Division by zero: which error

Dividing by zero with any of the three operators raises the ZeroDivisionError exception. This applies to both integers and fractions. You can catch it with try/except, or check the divisor in advance.

>>> 10 / 0
Traceback (most recent call last):
  ...
ZeroDivisionError: division by zero
>>> count = 0
>>> avg = 1500 / count if count else 0
>>> avg
0

Comparison operators

Comparisons return True or False. Equality is tested with two == signs; a single = is assignment. Strings are compared character by character using their character codes, so "B" < "a" is true: uppercase letters come before lowercase ones.

>>> 250 == 250.0
True
>>> 3 != 4
True
>>> 1 < 5 <= 10     # chain: 1 < 5 and 5 <= 10
True
>>> 0.1 + 0.2 == 0.3
False

Chained comparisons such as 0 <= x < 100 are a handy Python feature: you do not need to write and. The last line is a reminder about floating-point error: 0.1 + 0.2 gives 0.30000000000000004. Compare fractions with math.isclose(a, b), and store money in cents or in Decimal.

Logical operators and, or, not

Python's logical operators are written as words, not as the symbols && and || used in other languages. and is true when both parts are true, or is true when at least one part is true, and not flips the value.

aba and ba or bnot a
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue

Precedence: not first, then and, then or. The expression True or False and False equals True, because and is evaluated first. In complex conditions use brackets: it is clearer for you and for your colleagues.

What and and or actually return

and and or do not necessarily return True or False; they return one of the operands. or gives the first true value (or the last one if none is true), and and gives the first false value (or the last one). The false values are 0, 0.0, the empty string, empty collections, None and False.

>>> name = ""
>>> name or "Guest"
'Guest'
>>> 5 and 0
0
>>> not ""
True

Evaluation is lazy: if the result is already clear from the left side, the right side is not evaluated. That is why count and total / count does not fail with division by zero when count == 0. The not operator, unlike the other two, always returns a bool.

The is and in operators

== compares values, while is checks that two names refer to the same object. Two different empty baskets are equal, but they are not the same object. The one place where is is needed all the time is the check for None: if x is None.

>>> a = [250, 120]
>>> b = [250, 120]
>>> a == b, a is b
(True, False)
>>> c = a
>>> c is a
True

Do not compare numbers and strings with is: sometimes it appears to work because of internal object caching, but the result depends on the implementation, and Python emits a SyntaxWarning for constructs such as x is 5.

The in operator checks membership: a substring in a string, an element in a list, a key in a dictionary. not in is the reverse check.

>>> "coffee" in "coffee with milk"
True
>>> "food" in {"food": 450, "taxi": 300}
True
>>> 5 not in [1, 2, 3]
True

Assignment operators and the walrus operator :=

Compound operators such as +=, -=, *=, //= and others are shorthand: total += 250 means total = total + 250. Python has no ++ or -- operators: x++ causes a syntax error.

The walrus operator := (named for its resemblance to a walrus's eyes and tusks) assigns a value inside an expression. It is useful when you need a value both to test it and to use it afterwards:

items = ["coffee", "taxi", "lunch", "movie"]
if (n := len(items)) > 3:
    print(f"Too many expenses: {n}")

while (line := input("Amount: ")) != "":
    print(int(line) * 2)

Without the walrus you would have to call len twice or move the assignment to a separate line. Do not overuse it: if the line becomes hard to read, a plain assignment is better.

Rounding in Python: round, ceil, floor

For rounding in Python there is the built-in round function and functions from the math module. They solve different problems, and mixing them up is a common mistake.

FunctionWhat it does2.5-2.52.7
round(x)to the nearest, a half goes to the even number2-23
math.floor(x)down, towards minus infinity2-32
math.ceil(x)up, towards plus infinity3-23
math.trunc(x), int(x)drop the fraction, towards zero2-22

The round function in Python and banker's rounding

The function round(x, n) rounds to n digits after the decimal point; without a second argument it returns an integer int. The main trap: Python's round uses "banker's rounding", rounding a half to the nearest even number. So round(2.5) gives 2, while round(3.5) gives 4. This keeps rounding errors from accumulating in one direction over large calculations.

>>> round(2.5), round(3.5)
(2, 4)
>>> round(3.14159, 2)
3.14
>>> round(1250, -2)     # to hundreds
1200
>>> round(2.675, 2)     # not 2.68: in binary it is 2.67499...
2.67

If you need the familiar school rounding "half up", for example on a receipt, use Decimal with the ROUND_HALF_UP mode. Pass the number as a string, so you do not inherit the float error:

>>> from decimal import Decimal, ROUND_HALF_UP
>>> Decimal("2.5").quantize(Decimal("1"), ROUND_HALF_UP)
Decimal('3')
>>> Decimal("2.675").quantize(Decimal("0.01"), ROUND_HALF_UP)
Decimal('2.68')

One more rule from the course: round only when you display a value. For nice output you do not need round at all — an f-string is enough: f"{amount:.2f}" shows two digits, while the number itself stays exact.

math.ceil and math.floor: rounding up and down

math.ceil is needed when "not enough" is unacceptable: how many buses to order, how many pages a result list needs. math.floor is for when only complete units count. Both functions return an int.

import math

guests = 47
seats = 20
print(math.ceil(guests / seats))   # 3 buses
print(math.floor(9.99))            # 9
print(-(-guests // seats))         # 3 — ceil without math, using //

The math module has other useful functions too: math.sqrt (square root), math.isclose (comparing fractions), math.pi and math.gcd. Python 3.15 added the math.integer submodule (PEP 791) for integer maths: it contains comb, factorial, gcd, isqrt, lcm and perm, while the old math.gcd and others keep working.

The abs function: absolute value

abs(x) returns the absolute value: the distance from zero without the sign. No import is needed, the function is built in. It works with integers, fractions and even complex numbers: for 3+4j it returns the length of the vector, 5.0.

>>> abs(-250)
250
>>> abs(-12.5)
12.5
>>> budget, spent = 5000, 5320
>>> abs(budget - spent)    # how far off we are
320

A typical use is a difference regardless of direction, and comparison with a tolerance: abs(a - b) < 0.001. For fractions, math.isclose is more reliable, because it takes the scale of the numbers into account.

Operator precedence

When an expression contains several operators, Python evaluates them in order of precedence, from highest to lowest:

  1. **
  2. unary -x, +x, ~x
  3. * / // %
  4. + -
  5. bitwise shifts and operations
  6. comparisons, in, is
  7. not
  8. and
  9. or
  10. :=

So 2 + 3 * 4 equals 14, while (2 + 3) * 4 equals 20. If in doubt, add brackets: extra brackets cost nothing, while a precedence mistake can take a long time to find.

Common operator mistakes

MistakeWhat happensCorrect way
if x = 5:SyntaxError: this is an assignmentif x == 5:
2 ^ 3 instead of a powerbitwise XOR, result 12 ** 3
expecting an integer from 8 / 2you get 4.08 // 2
x == 1 or 2always true: it is (x == 1) or 2x in (1, 2)
expecting 3 from round(2.5)banker's rounding gives 2Decimal with ROUND_HALF_UP
"5" + 5TypeErrorint("5") + 5

Summary

Remember the key points: / always gives a float, // rounds down, % returns the remainder with the sign of the divisor, and exponentiation is **. The logical and, or and not are written as words and evaluated lazily, and is is needed to check for None. Python's round rounds half to the even number; for rounding up and down there are math.ceil and math.floor, and abs gives the absolute value. The course practises these operators in the expense tracker, where money is stored in cents.

FAQ

How do I round a number to two decimal places in Python?

Use round(x, 2). If you only need to display the number nicely, use an f-string such as f"{x:.2f}", which does not change the value itself.

Why does round(0.5) return 0 in Python?

Because round rounds a half to the nearest even number, and 0 is even; similarly round(1.5) and round(2.5) both give 2.

How do I get the integer part of a division in Python?

With the // operator: 17 // 5 gives 3. For negative numbers it rounds down, so -17 // 5 gives -4; if you want to drop the fraction towards zero, use int(-17 / 5).

Is there a ternary operator in Python?

Yes, it is the conditional expression: value_if_true if condition else value_if_false, for example "even" if n % 2 == 0 else "odd".

What is the difference between & and and in Python?

and is a logical operator with lazy evaluation, while & is a bitwise AND for numbers and an intersection for sets. In if conditions, use and.

Learn this topic on video

This topic is covered in depth with practice in the course “Python 3.15: от новичка до профи”.

Go to course