Rolando Andrade
Back to Content

Operators and Expressions in Programming: Precedence, Div and Mod Explained: Programming Fundamentals (5)

Learn arithmetic, relational and logical operators, operator precedence, integer division and modulo, and built in functions, with runnable examples.

· 8 min read
Operators and Expressions in Programming: Precedence, Div and Mod Explained: Programming Fundamentals (5)

An expression is a combination of values, variables, constants, operators and functions that the computer evaluates to produce one result. An operator is the symbol or word that says what to do with the values, like + to add or > to compare. The order in which the operators run is called precedence.

After this lesson, you can write the calculations and conditions your programs need, and predict their result before you run them.

In this lesson you will:

  • Use the arithmetic operators, including whole division (Div) and remainder (Mod).
  • Compare values with relational operators and combine conditions with And, Or and Not.
  • Predict the result of an expression with the rules of precedence.
  • Use built in functions like Sqrt, Abs, Round and Trunc.
  • Spot the operators that behave differently in StepCode and Python.

This lesson takes about 40 minutes. You only need a web browser.

Why precedence matters

What is 1 + 2 * 3? If you go from left to right, it is 9. If you multiply first, it is 7. A computer cannot guess, so every language fixes an order. With the usual rules of math, the answer is 7.

Most bugs in expressions are not typing mistakes. The code is valid, it runs, and it gives a wrong number because an operation ran before another one. The same happens in code written by AI agents. A formula with a missing pair of parentheses looks correct at a quick glance. To catch it, you need to read the expression the way the computer reads it.

Arithmetic operators

Arithmetic operators work with numbers.

Operation StepCode Python Example in StepCode Result
Addition a + b a + b 17 + 5 22
Subtraction a - b a - b 17 - 5 12
Multiplication a * b a * b 17 * 5 85
Division a / b a / b 17 / 5 3.4
Power a ^ b a ** b 2 ^ 3 8
Whole division a Div b a // b 17 Div 5 3
Remainder (modulo) a Mod b a % b 17 Mod 5 2

Division with / always gives a Real, even when both numbers are Integers. 10 / 4 is 2.5.

Whole division (Div) gives only the whole part of a division. Modulo (Mod) gives the remainder. Think of sharing 17 candies among 5 friends: each friend gets 17 Div 5, which is 3 candies, and 17 Mod 5, which is 2 candies, are left over. Both work only with Integers.

17 Div 5 = 3candies for each friend

17 Mod 5 = 2candies left over

Check: 5 × 3 + 2 = 17

Div is how many candies each friend gets. Mod is what is left when no more full rounds are possible. Move the sliders: the left over row never reaches the number of friends.

Mod is more useful than it looks. A number is even when n Mod 2 is 0. The last digit of a number is n Mod 10. And you can split a quantity into units, like seconds into minutes and seconds, as you will see in the practice. Loops uses the last digit trick to add the digits of a number.

Relational operators

Relational operators compare two values. The result is always a Boolean: True or False.

Comparison StepCode Python
Greater than a > b a > b
Less than a < b a < b
Greater than or equal a >= b a >= b
Less than or equal a <= b a <= b
Equal a = b a == b
Not equal a <> b a != b

In StepCode, you assign with the arrow (<-) and compare with =. In Python, you assign with = and compare with ==. Keep this in mind every time you move between the two.

Logical operators

Logical operators combine Booleans.

Operation StepCode Python It is True when
Negation Not a not a a is False
Conjunction a And b a and b both are True
Disjunction a Or b a or b at least one is True

A trick from the course: think of And as a multiplication and Or as an addition, with True as 1 and False as 0. If the result is 0, the answer is False. Otherwise, it is True.

  • True And False is 1 × 0 = 0, so False.
  • True And True is 1 × 1 = 1, so True.
  • True Or False is 1 + 0 = 1, so True.
  • False Or False is 0 + 0 = 0, so False.
  • True Or False And True is 1 + 0 × 1 = 1, so True.

The trick also explains the order. Multiplication comes before addition, and And comes before Or.

The order of precedence

When an expression has several operators, StepCode runs them in this order, from first to last:

  1. Parentheses ( ).
  2. Power ^.
  3. The negative sign, as in -x.
  4. Multiplication, division, Div and Mod: *, /, Div, Mod.
  5. Addition and subtraction: +, -.
  6. Comparisons: =, <>, <, <=, >, >=.
  7. Not.
  8. And.
  9. Or.

Operators at the same level run from left to right. So 6 / 2 * 3 is 3 * 3, which is 9. Power is the exception: 2 ^ 3 ^ 2 is 2 ^ 9, which is 512, because power groups from right to left.

For the arithmetic part, the course uses the memory aid PEDMAS: Parentheses, Exponents, Divisions, Multiplications, Additions, Subtractions. Division and multiplication share one level, and so do addition and subtraction.

Pick an expression below and press Next step to evaluate it the way StepCode does.

Step by step evaluation of expressions from the lesson. (1 + 2) * 3 > 7 And True: step 1, parentheses first, (1 + 2); step 2, then *, 3 * 3; step 3, then the comparison, 9 > 7; step 4, then And, True And True; result True. 1 + 2 * 3: step 1, * comes before +, 2 * 3; step 2, then +, 1 + 6; result 7. 6 / 2 * (2 + 1): step 1, parentheses first, (2 + 1); step 2, / and * share a level: left to right, 6 / 2; step 3, then the *, 3 * 3; result 9. 2 ^ 3 ^ 2: step 1, power groups right to left, 3 ^ 2; step 2, then the first ^, 2 ^ 9; result 512. True Or False And True: step 1, And comes before Or, False And True; step 2, then Or, True Or False; result True. Precedence in StepCode, first to last: parentheses, power, negative sign, multiplication, division, Div and Mod, then addition and subtraction, then comparisons, then Not, then And, then Or.

StepCode evaluates one operation at a time, following the precedence list, until a single value is left. Watch which level lights up at each step.

When you are not sure, add parentheses. They cost nothing, and the next person who reads the code (maybe you, maybe an AI agent asked to change it) will not have to guess.

Built in functions

Languages come with ready made functions for common tasks. These are some of the ones StepCode has:

Function What it does Example Result
Abs(x) Absolute value (the number without its sign) Abs(-4) 4
Sqrt(x) Square root Sqrt(16) 4
Round(x) Rounds to the nearest whole number Round(2.567) 3
Trunc(x) Drops the decimals Trunc(2.567) 2
Random() A random Real from 0 up to (not including) 1 Random() changes
PI The number π PI 3.141592653589793

StepCode also has Sin, Cos, Tan, Ln and Exp for math, and functions for text that you will meet in the strings lesson. In Python, abs() and round() are always available, and sqrt, sin, cos and pi come from the math library.

Guided practice

Each part is a complete program. Run it with the inputs given and compare the output.

1. Try every arithmetic operator

Edit the code and press Run to try it.

Run it, type 17 and then 5.

You should see:

Enter n1: 
Enter n2: 
Sum: 22
Difference: 12
Product: 85
Division: 3.4
Whole division: 3
Remainder: 2
Power: 1419857

2. Predict the result with precedence

This is the activity from class. Before you run it, write down the value of c, d and e on paper.

Edit the code and press Run to try it.

You should see:

c = 7
d = 9
e = 1

For c, the multiplication runs first: 1 + 6. For d, the parentheses run first, and then 6 / 2 * 3 goes from left to right: 3 * 3. For e, it is 6 / 2 / 3, from left to right: 3 / 3.

3. Combine conditions with logical operators

This continues the same class activity. f holds the result of a comparison, and the other variables combine it.

Edit the code and press Run to try it.

You should see:

f = True
g = False
h = True
i = True

(1 + 2) * 3 is 9, and 9 is greater than 7, so f is True. g is the opposite. h is True because at least one side is True. i is True because both sides are True.

4. Write a real condition

A cinema gives a discount to children under 12, people 65 or older, and students under 25. The parentheses make the student rule one group.

Edit the code and press Run to try it.

Run it with 20 and True. You should see:

Enter your age: 
Are you a student? (True or False): 
Discount: True

Run it again with 30 and True. You should see:

Enter your age: 
Are you a student? (True or False): 
Discount: False

Try more ages without running the program each time. Every part of the rule shows its own value.

discount = True because isStudent And age < 25 is True

Or needs only one True part. The student part is a group: both isStudent and age < 25 must be True. Try age 24 and age 25 as a student.

5. Split seconds with Div and Mod

A video lasts 3725 seconds. How long is that in hours, minutes and seconds? Div gives the whole units, and Mod gives what is left for the next, smaller unit.

Edit the code and press Run to try it.

Run it and type 3725. You should see:

Enter a number of seconds: 
3725 seconds is 1 h 2 min 5 s

In the next lesson, Input, process and output, you build this same program again, one part at a time, and turn it into a clock.

6. Use built in functions in a formula

The quadratic formula finds the values of x where ax² + bx + c = 0. It needs a square root, so it uses Sqrt. Notice how the parentheses keep the whole top part over the whole bottom part.

Edit the code and press Run to try it.

Run it with 1, -3 and 2. You should see:

Enter a: 
Enter b: 
Enter c: 
Root 1: 2
Root 2: 1

Remove the parentheses around 2 * a and run it again. The program still runs, but / 2 * a now divides by 2 and then multiplies by a. With a equal to 1 you will not notice, because dividing by 2 and multiplying by 1 gives the same answer. Now try 2, -6 and 4. That equation has the same roots, 2 and 1, but the program without parentheses shows:

Enter a: 
Enter b: 
Enter c: 
Root 1: 8
Root 2: 4

That is the kind of bug that passes a quick look and a test with easy numbers.

Common mistakes

If you see "==" is not part of StepCode: write "=" to compare two values., it means you used the Python way to compare. In StepCode, comparison uses a single =.

If you see Comparisons cannot be chained: write "a < b And b < c"., it means you wrote something like 1 < x < 10. In math that is normal, but a computer evaluates 1 < x first and gets a Boolean, which cannot be compared with 10. Write 1 < x And x < 10.

If you see "Mod" only works with Integer: convert first with "Trunc" or "Round"., it means one side of Mod (or Div) is a Real. Whole division and remainder only make sense for whole numbers.

If you see A Real cannot be stored where a Integer is expected: "Div" gives the whole division., it means you stored the result of / in an Integer variable. Use Div if you want the whole part, or make the variable Real.

If you see "+" does not mix text and numbers: convert the number with "ToText"., it means you tried something like "Age: " + 5. Convert the number with ToText(5), or show both with Write "Age: ", 5;.

If you see This divides by zero: "/" received a divisor equal to 0. while the program runs, it means the divisor was 0. That is the runtime error from the first lesson, and no language can divide by zero. Check the value before you divide. The conditionals lesson shows how.

Boundaries

Operators are not the same in every language, even when they look alike. Here are three real differences between StepCode and Python. Run them in StepCode:

Edit the code and press Run to try it.

You should see:

-7 Div 2 = -3
-7 Mod 2 = -1
Round(2.5) = 3

Now the same in Python:

print(-7 // 2, -7 % 2, round(2.5))

You should see:

-4 1 2
-5 -4 -3 -2 -1 0 1 2 3 4 5 StepCode Div: -3 Python //: -4 n / 2 = -3.5

StepCode-7 Div 2 = -3, -7 Mod 2 = -1

Python-7 // 2 = -4, -7 % 2 = 1

Above the line, StepCode cuts toward zero. Below it, Python goes down to the smaller number. For negative odd numbers they land on different answers.

StepCode cuts the decimals toward zero, so -7 Div 2 is -3. Python rounds down, toward the smaller number, so -7 // 2 is -4, and the remainder changes to match. Python’s round() also sends a value that ends in .5 to the nearest even number, so round(2.5) is 2. With positive numbers that do not end in .5, both languages agree, so these differences hide well. When an AI translates code from one language to another, this is exactly where a wrong result can slip in.

Also keep in mind the difference between / and Div. They are not two spellings of the same thing. / gives a Real with decimals, Div gives an Integer without them.

Finally, = in StepCode compares and never assigns. The arrow <- is the only way to store a value.

Practice exercises

These come from the practice guide of the unit.

Exercise 1. Evaluate by hand. Compute each expression on paper, then check your answers by running the program.

Edit the code and press Run to try it.
Solution
a) 53
b) -8
c) 9
d) 12
e) 7
f) 90

For e), the power runs first inside the parentheses: 18 - 16 is 2, then 2 * 2 is 4, then 3 + 4 is 7.

Exercise 2. Deduce each result. With a = 5, b = 25 and c = 10, what does each line show?

Edit the code and press Run to try it.
Solution
40
255
7.5
7
10
3
7.5

b Div c is 2 and b Mod c is 5, and both run before the addition. In the sixth line, the parentheses make the addition run first: 30 Div 10 is 3.

Exercise 3. Write it as an expression. Write each formula on one line, the way a program needs it. Use Sqrt for the square root.

  1. m divided by n, plus p.
  2. m plus n divided by (p minus q).
  3. (m plus n) divided by (p minus q).
  4. The quadratic formula with the plus sign.
Solution
  1. m / n + p
  2. m + n / (p - q)
  3. (m + n) / (p - q)
  4. (-b + Sqrt(b ^ 2 - 4 * a * c)) / (2 * a)

Exercise 4. Even or odd. Write a program that reads a whole number and shows whether it is even, using Mod.

Solution
Edit the code and press Run to try it.

With 14, you should see:

Enter a whole number: 
14 is even: True

With 7, you should see:

Enter a whole number: 
7 is even: False

What you learned

  • An expression combines values, variables, operators and functions into one result.
  • / always gives a Real, Div gives the whole part and Mod gives the remainder.
  • Relational operators give a Boolean, and Not, And and Or combine Booleans.
  • Precedence decides the order: parentheses, power, multiplication and division, addition and subtraction, comparisons, then Not, And and Or.
  • Operators can behave differently between languages, so check negative numbers and rounding when you translate code.

Next steps

In the next lesson, Input, process and output, you will put variables and expressions together into complete programs that read data, compute and show a result.