Skip to content

Operators



Why we need operators

Analogy

  • If variables are the nouns of your program, operators are the verbs. They are the symbols that actually do something to your values.
  • You already know most of them from a calculator: plus, minus, times.
  • The interesting ones are the handful that behave differently from what school taught you, and those are what this chapter spends its time on.

The arithmetic ones

OperatorDoesExample
+Add7 + 2 gives 9
-Subtract7 - 2 gives 5
*Multiply7 * 2 gives 14
/Divide7 / 2 gives 3.5
%Remainder7 % 2 gives 1
//Divide and chop the decimal7 // 2 gives 3

There is a power operator too, written ** in Python and Math.pow in Java, so 7 ** 2 is 49.

Two of these need a proper explanation, and they are the two that cause bugs.


The division trap

In Python 3, 7 / 2 gives 3.5. Sensible.

In C, C++ and Java, 7 / 2 gives 3. Not 3.5, and not rounded to 4. When you divide an integer by an integer in those languages the answer must also be an integer, so the decimal part is simply thrown away.

Code
int result = 7 / 2;      // 3double result = 7 / 2;   // still 3.0, the damage was already donedouble result = 7.0 / 2; // 3.5, now it works

Make one side a decimal and the problem disappears. This one is nasty because nothing crashes: your program keeps running and quietly gives wrong answers.


The remainder, and what it is really for

% gives you what is left over after division. 17 % 5 is 2, because 5 goes into 17 three times with 2 remaining.

That sounds like a school exercise. It is actually one of the most used operators in programming, and the picture below is why.

Which part runs first2 + 3 * 4 ** 2the power binds tightest2 + 3 * 16then multiply2 + 48and add last50What % is really for01234567891011(11 + 1) % 12 = 0past the end, and back to the start

Three things it does constantly:

  • Even or odd. n % 2 == 0 means even.
  • Divisible by. n % 5 == 0 means n is a multiple of 5.
  • Wrapping round. (current + 1) % size snaps back to 0 when it reaches the end. If you ever build a circular queue, that single line is the whole idea.

Watch out

With negative numbers, % behaves differently across languages. -7 % 3 is 2 in Python and -1 in C and Java. Check before you rely on it.


Assignment shortcuts

= puts a value in. The rest are pure convenience, and they read well.

Code
count = 10 count += 5    # same as count = count + 5   → 15count -= 3    # same as count = count - 3   → 12count *= 2    # same as count = count * 2   → 24

C, C++, Java and JavaScript also have ++ and -- for adding or subtracting one. There is a difference between i++ and ++i: the first gives the old value and then increments, the second increments first. Use them on their own line and you will never have to think about it. Python has no ++ - write i += 1.


Comparison

These ask a question and always answer with a boolean.

OperatorAsks5 and 3
==Are they equal?False
!=Are they different?True
>Is left bigger?True
<Is left smaller?False
>=Bigger or equal?True
<=Smaller or equal?False

The one to burn in: = puts a value in, == asks whether two things match. In C and older Java, if (x = 5) compiles fine and quietly assigns 5 to x. The condition is then always true and your program misbehaves for reasons you cannot see.


Logical operators, and the one trick worth knowing

and needs both sides true. or needs at least one. not flips it. In C, Java and JavaScript those are written &&, || and !.

The everyday mistake is writing or where you meant and. Read the condition out loud in English: "age is at least 18 or they have an ID" lets a ten-year-old with an ID card through.

Now the trick, which is rarely taught and genuinely useful.

Definition

Short-circuit evaluation. When the computer works out A and B, it checks A first. If A is false the whole thing is already false whatever B says, so B is never evaluated at all. The same goes for or when the left side is true.

That is not just a speed optimisation. You can lean on it:

Code
if user is not None and user.age > 18:

If user is None, the second half would crash. It never runs, because the first half already failed. Order matters here - swap the two halves and the program breaks.


Precedence

Operators run in a fixed order, the same way 2 + 3 * 4 is 14 and not 20. Roughly: brackets, then powers, then multiply and divide, then add and subtract, then comparisons, then not, and, or.

Do not memorise that list. Memorise the practical rule instead:

Note

When you are even slightly unsure, add brackets. Nobody has ever been confused by too many brackets. Plenty of people have been burned by too few.


Mistakes to watch for

Watch out

  • = instead of == in a condition.
  • Integer division giving whole numbers in C and Java when you expected decimals.
  • Comparing floats with ==. 0.1 + 0.2 == 0.3 is false.
  • Using & instead of && for boolean logic. One works on bits, the other on booleans.
  • Mixing up and and or.
  • Chained comparisons. 1 < x < 10 works in Python and does something completely different in C and Java.

Quick recap

  • Operators are the verbs: they act on values and produce new ones
  • / truncates when both sides are integers in C and Java
  • % is a remainder, and it is how you make anything wrap round
  • = assigns, == compares
  • and and or short-circuit, which you can rely on deliberately
  • When unsure about order, use brackets

Key takeaway

The equals sign puts a value in, the double equals asks a question, and the percent sign tells you what is left over.