An Introduction to Python For Undergraduate Engineers/Python as a Calculator
Firstly, let's just quickly see how you can do simple arithmetic in Python. The table below list the basic mathematical operators and the associated code in python.
Function | Code | Example | Result | Function | Code | Example | Result | |
---|---|---|---|---|---|---|---|---|
Addition | + | 2+3 | 5 | Multiplication | * | 5*6 | 30 | |
Integer Division | / | 8/3 | 2 | Floating Point Division | / | 8.0/3 | 2.666... | |
Remainder after division | % | 8%3 | 2 | Exponential | ** | 3**2 | 9 |
For more complex arithmetic, python contains a special module called math. This module contains an array of different functions (such as square root) and constants (such as pi). To use a module, we must first import it, like so:
import math
We can then use for example:
math.sqrt(16) #to find the square root of 16. math.pi #to get the value of pi.
Alternatively you can import modules in the following way:
from math import *
This will import everything from the math module directly allowing us instead to call the functions as follows:
sqrt(16) to find the square root of 16. pi to get the value of pi.