Tutorial - Python 3 basics
Python as calculator
Posted September 25, 2018 by Rokas Balsys
Math in python is so popular and it works extremely simply. Python interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: most popular operators +, -, * and / work just like in most other languages. Parentheses "(())" can be used for grouping. Example:
>>> 6 + 6 # Here is simple addition, the returned number is 12. 12 >>> 77 - 6*6 # Multiplication and subtraction, the returned number is 41. 41 >>> 55 / 16 # Division always returns a floating point number. 3.4375 >>> (77 - 6*6) / 4 # More complex calculation. 10.25
With Python, it is possible to use more complex math to get floor division or exponent numbers, it's very similar to standard math functions, but sometimes it's easier to do what you need, when you use them rather than not using them:
>>> 9//2 # This gives us as output the greatest integer number. 4 >>> 9**2 # This is exponent multiplication. Exponentiation corresponds to repeated multiplication. 81 >>> 9%2 # This is modulo. The modulo operation finds what's left after division of one number by another 1 >>> abs(-9) # This gives us positive number. SImply if number is negative, it removes minus from it. 9
One of the common math function is Square root. For example, the principal square root of 9 is 3, which is denoted by √9 = 3, because 32 = 3 • 3 = 9 and 3 is nonnegative.
>>> math.sqrt(25) 5
In order to use the math.sqrt() function, you must explicitly tell Python that you want it to load the math module. To do that, you must import math library, to do so add this line on top of python code:
Order of operations:
Python uses the standard order of operations as taught in Algebra and Geometry classes at high school, secondary school, university and etc. Mathematical expressions are evaluated in the following order (memorized by many as PEMDAS), which is also applied to parentheticals.
( ... )- Before operating on anything else, Python must evaluate all parentheticals starting at the innermost level. (This includes functions.)
**- As an exponent is simply short multiplication or division, it should be evaluated before them.
Multiplication and Division -
* / // %- Again, multiplication is rapid addition and must, therefore, happen first.
Addition and Subtraction -
+ -- Nothing to tell about this, that's basics of basics.
Now we covered the basics of math. It's quite simple, isn't it? There is more about math, but then we need to cover more than basics, this includes math library, but we will cover this in future. Now you can move to next tutorial: