Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

Operators: remainder (modulo)

The next operator is quote a peculiar one, because it has no equivalent among traditional arithmetic operators. 

Its graphical representation is Python is the % (percent) sign, which may look a bit confusing. 

Try to think of it as a slash (division operator) accompanied by two funny circles. 

The result of the operator is a remainder left after the integer division. 

In other words, it's the value left over after dividing one value by another to produce an integer quotient. 

Note: the operator is sometimes called modulo in other programming languages. 

Take a look at the snippet - try to predict its result and then run it: 

print(14%4)

As you can see, the result is two.

2

This is why:

  • 14//4 gives 3 -> this is the integer quotient
  • 3*4 gives 12 -> as a result of quotient and divisor multiplication
  • 14-12 gives 2 -> this is the remainder

This example is somewhat more complicated: 

print(12 % 4.5)

What is ther result? 

3.0 - not 3 but 3.0 (the rule still works: 12 // 4.5 gives 2.0; 2.0 * 4.5 gives 9.0; 12 - 9.0 gives 3.0)

Operators: how not to divide

As you probably know, division by zero doesn't work. 

Do not try to; 

  • perform a division by zero
  • perform an integer division by zero
  • find a remainder of a division by zero

 

Operators: addition

The addition operator is the+ (plus)  sign, which is fully in line with mathematical standards. 

Again, take a look at the snippet of the program below: 

 

print(-4 + 4)

print(-4. + 8)

The result should be nothing surprising. Run the code to check it. 

0

4.0

The subtraction operator, unary and binary operators

The subtraction operator is obviously the - (minus) sign, although you should note that this operator has another meaning - it can change the sign of a number.

This is a great opportunity to present a very important distinction between unary and binary operators. 

In subtracting applications, the minus operator expects two arguments: the left (a minuend in arithmetical terms) and right (a subtrahend).

For this reason, the subtraction operator is considered to be one of the binary operators, just like the addition multiplication and division operators. 

But the minus operator may be used in a different (unary) way - take a look at the last line of snippet below: 

 

print(-4 - 4)
print(4. - 8)
print(-1.1)

By the way: there is also a unary + operator, You can use it like this: 

print(+2)

The operator preserves the sign of its only argument - the right one.

Although such a construction is syntactically correct, using it doesn't make much sense, and it would be hard to find a good rationale for doing so. 

Take a look at the snippet abor - can you guess its output?