6 Arithmetic

Numbers and variables can be combined to perform basic arithmetic. For example

b =  4 + 7/3

This will make variable b equal to 4 + 2  = 6

Incrementing a Variable

You can also do tricks like this

a = a + 1

Which assigns variable a to be the current value of variable a plus 1 . Which in simple words means increase a by 1 , or increment a by 1

It is important to understand in most computer languages that = is the assignment operator. It means save what ever is on the right side into the variable on the left side.  Which is not the same as the = you would use in a mathematical equation.

Brackets

Brackets are used to make sure the statement is calculated in the correct order. When in doubt about which order the calculation is performed use brackets to make it work in the order you want. Just remember that everything inside the brackets is calculated first.

c = 4
a =  c + 7 / 3  # which gives the answer  a = 4 + 2  = 6
a = (c + 7)/ 3  # which gives the answer  a = 11/3   = 3

These two examples produce different results. In the first c is added to 7/3 , while in the second c is added to 7 and the resulting sum is divided by 3.  (This is because multiplications and divisions are done before the additions and subtractions.)

Arithmetic Functions

These arithmetic functions can be used

+    Add           ( a = b + c )
     Subtract   ( a = b – c)
*     Multiply     ( a = b * c)
/     Divide        ( a = b / c)
%   Modulo    (calculates the remainder,   7 % 4  equals 3)

Example:

hours   = 19
minutes = 45
mins_total = ( hours * 60 ) + minutes   # equals 1185
print hours, minutes, mins_total

This statement calculates the total number of minutes in 19 hours 45 minutes. (Dont forget to press the Launchpad RESET button when running this example)

mins_total = 1185
hours   = mins_total / 60     # = 19
minutes = mins_total % 60     # = 45
print mins_total, hours, minutes

This equation does the reverse calculation, it calculates the hours and minutes  in 1185 minutes.