Python as a fancy calculator
Python as a fancy calculator
Python can be used as a fancy calculator to complete arithmetic problems that include addition, subtraction, multiplication and division. Python can also be used for trigonometric calculations and statistical calculations.
Arithmetic
Python can be used as a calculator to make simple and complex calculations.
Calculations can be accomplished at the Python Prompt. The Python prompt is often called the Python REPL, which stands for Read Evaluate Print Loop. The Python REPL shows three arrow symbols >>>
, called a prompt, before a blinking cursor.
>>>
Programmers type commands at the prompt, then hit [ENTER] to run the commands. A command entered at the prompt is Read by the Python interpreter, results of running the command are Evaluated, then Printed to the command window. After the output, a new >>>
prompt appears on a new line. This process repeats over and over again in a Loop. Note the triple arrow signs >>>
do not need to be typed. >>>
is used to indicate the Python prompt, not shown as a command the user types.
In Python, addition of two numbers is accomplished using the plus +
sign. Type the following command at the Python prompt. Keying in [Enter] after typing the command to executes the command.
>>> 5 + 3
8
Subtraction in Python is completed using the minus -
sign. Try the following command at the Python prompt. Press [Enter] to run the command.
>>> 8 - 1.5
6.5
Multiplication in Python is run using the asterisk *
sign. Note the asterisk sign must be used for multiplication. Using an x 5 x 2
or parenthesis (5)(2)
will note work when using Python.
>>> 5 * 2
10
Divising is accomplished with the forward slash /
.
>>> 5 /2
2.5
If the battery has a mass of 5000 g and a volume of 2500 cm^3 What is the density of the battery? The formula for density is below, where D is density, m is mass and v is volume.
In the problem above m = 5000 and v = 2500
Let's solve this with Python at the Python prompt. Remember you do not need to type the three arrow symbols >>>
. The symbols are their to indicate the prompt, not a command for the user to type.
>>> 5000 / 2500
2.0
In Python, exponents (raising a number to a power) are calculated are calucated with the double asterisk symbol **
. Note that the circumflex symbol ^
(or "hat" symbol) is not used for exponents in Python.
>>> 5 ** 2
25
Python saves the result of the previous calculation as the underscore _ character. The underscore _ character can be used in the next command (similar to ans
in MATLAB)
>>> 2 * 3
6
>>> _ + 1
7
Section Summary
A summary of the arithmetic operations in Python are below.
operator | meaning | example | result |
---|---|---|---|
+ |
addition | 5 + 2 |
7 |
- |
subtraction | 5 - 2 |
3 |
* |
multiplication | 5 * 2 |
10 |
/ |
division | 5 / 2 |
2.5 |
** |
exponent | 5**2 |
25 |
_ |
previous result | _ + 2 |
27 |
### Absolute Value and Powers |
Python's abs()
function outputs the absolute value of a number. abs()
is an example of a function. Functions are a core component of many programing languages. Functions allow sections of code to be encapsulated in one command. In Python, functions have three parts, some of which are optional.
output = function_name(input_arguments)
One required part of each function is a name. All functions need a name so that the can be called in a program or entered in the Python REPL. The name of the abs()
function is abs
.
An optional part of each function is input arguments. Input arguments are values, variables or objects passed to the function as input. In Python, input arguments are supplied to functions within parenthesis ( )
following the function name. For instance, in the function call abs(-5)
, the input argument is the number -5
. Some functions can accept mulitple input arguments and some functions don't accept any input arguments. Functions which don't accept any input arguments still need to have the parenthesis included, but nothing is included within the parenthesis. For example abs()
.
An optional part of each function is output. The output of a function is the what the function produces when it is run. For example, the output of abs(-5)
is 5
, since the absolute value of -5
is 5
. The output of a function will be printed out to the Python REPL
>>> abs(-5)
5
Python's powers function pow()
accepts two input arguments. pow(5,2)
is equivalent to 5^2 which equals 25. In the code below, pow
is the function name, 5,2
are the input arguments and 25
is the output.
>>> pow(5,2)
25
Section Summary
A summary of the built-in fuctions abs()
are pow()
is below.
function | meaning | example | result |
---|---|---|---|
abs() |
absolute value | abs(-4) |
4 |
pow(5,2) |
raise a number to a power | pow(5,2) |
25 |
Trig: sin, cos, tan
Python as a fancy calculator is not limited to simple arithmetic. The trigonometry functions sine, cosine and tangent are also available. In order to use these trigonometry functions, we need to learn a concept: importing modules.
In Python there are many functions built into the language when it starts. These include +
,-
, *
, /
, abs()
, and pow()
like we saw in the previous section. However, not all functions work right when the Python REPL starts. Say we want to find the sine of an angle. Try the following:
>>> sin(60)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sin' is not defined
This error is returned because we have not told python to include the sin function. The sine function is part of the Python Standard Library. The Python Standard Library comes with every Python installation and includes many functions, but not all of these functions are available when the Python REPL starts. In order to use the sine function, first import sin
from math module. The math module is part of the Python Standard Library.
Importing modules and functions is easy. Use the following syntax: from module_name
import function_name
.
To import the sin
function from the math module try:
>>> from math import sin
>>> sin(60)
-0.3048106211022167
Success! You can also import multiple functions at once. Say we want to use a couple different trig functions to solve the following problem.
A vector is at an angle of pi/6 radians. What is the sin, cos and tan of the angle?
To solve the problem we need to import the sin
, cos
, and tan
functions from the math module. It would also be useful to have the value of pi, rather than having to write 3.14.... We can import all of these functions at the same time by placing commas in between the function names.
Try:
>>> from math import sin, cos, tan, pi
>>> pi
3.141592653589793
>>> pi/4
0.7853981633974483
>>> sin(pi/4)
0.7853981633974483
>>> sin(2*pi)
Section Summary
A summary of some of the trig functions in Python's math
module are below.
function | meaning | example | result |
---|---|---|---|
sin() |
sine of an angle (in radians) | sin(pi/2) |
1.0 |
cos() |
cosine of an angle (in radians) | cos(pi) |
-1.0 |
tan() |
tangent of an angle (in radians) | tan(pi/2) |
1.0 |
pi |
mathemtatical contstant \pi | pi |
3.141592... |
Additional trigonometry functions are summarized at the end of this section.
Exponents and Logarithms
It is easy to calculate exponents and logarithms in Python. Note that Python exponent and logarithm functions (except for pow()
) need to be imported from the math module before the functions are used.
The following exponent and logarithm functions can be imported from the math module:
log()
log10()
exp()
e
pow()
sqrt
Let's try and example:
A triangle has sides measuring 3 and 4. What is the length of the hypotenuse?
>> from math import sqrt
>>> sqrt(3**2 + 4**2)
5.0
The exp()
function raises the mathematical constant e (Euler's constant) to a power. The function call exp(5)
is equivalent to e^5.
>>> from math import exp
>>>exp(5)
148.4131591025766
In Python, the log()
function calculates natural logs (log base e) and the log10()
function calculates base 10 logs.
from math import log, log10, e
>>> log(e)
1
>>> log10(10)
1
The number of vacancies in a metal crystal structure can be estimated using the following equation:
Given the following parameters, calculate n, the number of vacancies in Copper at 20 degrees C.
n_v = 2.0^{-0.3}
Q_v = 5000
R = 3.18
T = 293
To find the answer to this problem, we need to use the exp
function from the math module. exp
needs to be imported before making the calculation.
>>> from math import exp
2.0**(-0.3)*exp(-5000/(3.18*293))
0.0037943276214106973
Statistics
To round out this section, we will look at a couple of Python's statistics functions. Python's statistics functions are part of the Python Standard Library, but not part of the math module. To access Python's statistics functions, the statistic functions need to import from the statistics module. Use the statement from statistics import mean, median, mode, stdev
. Then the functions mean
, median
, mode
and stdev
(standard deviation) can be used.
>>> from statistics import mean, median, mode, stdev
>>> test_scores = [60, 83, 83, 91, 100]
>>> mean(test_scores)
83.4
>>> median(test_scores)
83
>>> mode(test_scores)
83
>>> stdev(test_scores) # standard deviation of a sample
14.842506526863986
Section Summary
The statistics functions in the table below are part of Python's statistics module which is included in the Python Standard Library.
function | description |
---|---|
mean() |
mean (average) |
median() |
median (middle value) |
mode() |
(most often) |
stdev() |
standard deviation of a sample |