Calculations are very important in programming. Calculations can be done on the numeric types: ints and floats. Python supports the 4 basic arithmetic operators: +, - , *, /. For example: 3 * 4 returns 12.
Python also supports exponentiation (powers) with the ** operator. For example: 3 ** 2 returns 9.
Note: There is a separate square root function, but don't forget you can use the .5 power to take square roots.
Keep in mind that there is no implied multiplication in programming languages. All multiplication must be written explicitly with a multiplication symbol. This means that 3x must be written 3 * x and 3(x + 4) must be written 3 * (x + 4).
The x//y returns the integer quotient from "floor division" of x divided by y.
The x%y returns the remainder after dividing x by y.
We will talk about this more in a later section.
You may be familiar with order of operations from math. Python will use a similar order to PEMDAS.
Parentheses (and other grouping symbols)
Exponents
Multiplication/Division/Modulus
Addition/Subtraction
The order of operations for grouping symbols (), {}, [], <> is inside to outside. Otherwise, the order is left to right.
This includes those used by functions!
Example One: 3 * (4 + (2 + 2))
First the inside parentheses are calculated: 2 + 2
3 * (4 +4)
Then the outside parentheses are calculated: 4 + 4
3 * 8
Then the other operations are done.
24
Example Two: int(input("Input an integer"))
This is not operated left to right! It is operated inside to outside.
First, the input function is called. Then, the string returned by the input is converted to an int!
Absolute value can be used to force values to always be positive.
abs(num)
To find the distance between two numbers (1 dimensional distance) you just subtract and take absolute value.
abs( x - y )
To round a float to a certain number of decimal places use:
round( num, places )
For example, round(4.31689, 2) would return 4.32.