Introduction to Python Programming. Section 2. Using Python as a Scientific Calculator
2 Using Python as a Scientific Calculator
2.1 Objectives
In this section you will learn:
- How to use Python for elementary and advanced math calculations.
- How to use the floor division and modulo operations.
- How to import the Numpy library and work with mathematical functions.
- How to work with fractions, random numbers and complex numbers.
- About finite computer arithmetic and rounding.
2.2 Why use Python as a calculator?
Python can be used as an advanced scientific calculator, no need to own a TI-89 ($140 value). Moreover, a TI-89 hardly can compete with the processing power of a desktop computer. In this section we will show you how to use this computing power - no programming needed. Let us begin with the simplest math operations.
2.3 Addition and subtraction
Launch the Python app on NCLab’s virtual desktop, erase the demo script, type 3 + 6 and press the Play button. You should see what’s shown in Fig. 4:
Of course you can add real numbers too:
Two numbers can be subtracted using the minus sign:
2.4 Multiplication
Multiplication is done using the asterisk ’*’ symbol as in
Indeed, real numbers can be multiplied as well:
2.5 Division
The forward slash ’/’ symbol is used for division:
2.6 Floor division
The floor division a // b returns the closest integer below a / b:
It can be used with real numbers as well - in this case it returns a real number with no
decimal part:
Technically, the result of the former example was integer (int) and the result of the latter
was a real number (float). This has no influence on the accuracy of the calculation.
Last, when one of the numbers a, b is negative, then the floor division a // b again returns
the closest integer below a / b:
People who interpret floor division incorrectly as "forgetting the decimal part of the result" are sometimes confused by this behavior.
2.7 Modulo
Modulo is the remainder after floor division, and often it is used together with the floor
division. In Python, modulo is represented via the percent symbol ’%’:
Modulo can be applied to real numbers as well:
2.8 Powers
For exponents, such as in 24, Python has a double-star symbol ’**’:
Both the base and the exponent can be real numbers:
But one has to be careful with negative numbers:
Calculating

2.9 Priority of operations
Python follows the standard priority of math operations:
- Round brackets ’(...)’ have the highest priority,
- then exponentiation ’**’,
- then multiplication ’*’, division ’/’, floor division ’//’, and modulo ’%’,
- the lowest priority have addition ’+’ and subtraction ’-’,
- operations with the same priority are evaluated from left to right – for example the result of 20 / 10 * 2 is 4.
Note that no other brackets such as { } and [ ] are admissible in mathematical expressions.
The reason is that they have a different meaning in the programming language.
To illustrate the priority of operations, let’s evaluate the following expression:
If you are not sure, it never hurts to use round brackets:
And as a last example, let’s calculate

If you are not sure about the expression 20 / 4 / 5, then note that 20 is first divided by 4 and the result (which is 5) is then again divided by 5. Therefore typing 20 / 4 / 5 is the same as typing 20 / (4 * 5).
2.10 Using empty spaces makes your code more readable
Your code will be much easier to read if you use empty spaces on either side of arithmetic
symbols, as well as after commas. In other words, you should never write congested code
such as
The same can be written much more elegantly as
2.11 Importing the Numpy library
In order to calculate square roots, exponentials, sines, cosines, tangents, and many other
math functions, the best way is to import Numpy. Numpy is a powerful Python library for
numerical computations. To import it, just include the following line at the beginning of your
code:
Here numpy is the name of the library, and np is its standard abbreviation (you could use a
different one if you wanted). After Numpy is imported, one can calculate, for example,
e2:
As you could see, one needs to add a prefix ’np.’ to the exp function to make it clear where the exp() function is coming from.
2.12 Finite computer arithmetic
The reader surely knows that the cosine of 90 degrees (which is 90π∕180 radians) is 0.
However, when typing
one obtains
The reason is that:
The computer cannot represent π exactly because it has infinitely many decimal
digits. The cosine function also cannot be calculated exactly because it involves the
summation of an infinite (Taylor) series.
It is important to get used to the fact that arithmetic calculations sometimes may yield "strange" values like this. In reality they are not strange though - on the contrary - they are natural. Because this is how computer arithmetic works. The reason why one usually does not see such numbers when using standard pocket calculators is that they automatically round the results. However, this is not a choice that should be made by the device - whether round the result or not, and to how many decimal places - should be the user’s choice. And that’s exactly how Python does it.
2.13 Rounding numbers
Python has a built-in function round(x, n) to round a number x to n decimal digits. For
example:
Back to our example of cos(90π∕180):
And last - the number of decimal digits n can be left out. Then the default value n = 0 is
used:
2.14 List of math functions and constants
Elementary functions (and constants) that one can import from Numpy are listed
below. We also show their arguments for clarity, but the functions are imported
without them. Remember, the Numpy library is imported via import numpy as
np.
pi | np.pi | π |
e | np.e | e |
arccos(x) | np.arccos | inverse cosine of x |
arccosh(x) | np.arccosh | inverse hyperbolic cosine of x |
arcsin(x) | np.arcsin | inverse sine of x |
arcsinh(x) | np.arcsinh | inverse hyperbolic sine of x |
arctan(x) | np.arctan | inverse tangent of x |
arctanh(x) | np.arctanh | inverse hyperbolic tangent of x |
arctan2(x1, x2) | np.arctan2 | arc tangent of x1∕x2 choosing the quadrant correctly |
cos(x) | np.cos | cosine of x |
cosh(x) | np.cosh | hyperbolic tangent of x |
exp(x) | np.exp | ex |
log(x) | np.log | natural logarithm of x |
pow(a, b) | np.pow | ab (same as "a**b") |
sin(x) | np.sin | sine of x |
sinh(x) | np.sinh | hyperbolic sine of x |
sqrt(x) | np.sqrt | square root of x |
tan(x) | np.tan | tangent of x |
tanh(x) | np.tanh | hyperbolic tangent of x |
In summary:
Python provides many readily available mathematical functions via the Numpy
library. To use them, import Numpy via the command import numpy as np.
For additional functions visit https://docs.scipy.org/doc/numpy-1.14.0/
reference/routines.math.html.
2.15 Using the Fractions library
Let’s import the Fractions library as fr:
Then a fraction such as 4/7 can be defined simply as fr.Fraction(4, 7). Fractions can
then be added, subtracted, multiplied and divided as you would expect. The result of such an
operation always is a fr.Fraction again. For example:
Another example:
The Fractions library also provides a useful function gcd() to calculate the Greatest
Common Divisor (GCD) of two integers. For illustration let us calculate the GCD of 867 and
629:
For the full documentation on the Fractions library visit https://docs.python.org/ 3.1/library/fractions.html.
2.16 Working with random numbers
Python provides a random number generator via the random() function that can be
imported from the Random library. First let’s import the library as rn:
The random() function returns a random real number between 0 and 1. Calling
five times yields
0.016865272219651395
0.7551082761266997
0.5599940035041735
0.6110871965133025
Of course, you will get different values. When we need a random number in a
different interval, for example between 10 and 15, then we multiply the result of
random() by the length of the interval (here 5) and add the left end point (here
10):
Again let’s evaluate the above code 5 times:
11.076556529787744
14.092310626104025
14.426494859235547
13.768444261074983
Sometimes we need to generate random integers rather than real numbers. This can be done
via the randint() function. For illustration, a random integer between 1 and 3 can be
generated via the code
Evaluating the code five times, one obtains a sequence of random numbers:
3
2
1
3
The Random library has a lot of additional functionality. For the full documentation visit https://docs.python.org/3/library/random.html.
2.17 Complex numbers
Appending ’j’ or ’J’ to a real number makes it imaginary. Let’s calculate i2 which in Python
is represented as -1 + 0j:
Complex numbers are always represented as two floating point numbers, the real part and
the imaginary part:
One can also define them using the built-in function complex():
All arithmetic operations that are used for real numbers can be used for complex numbers as
well, for example:
To extract the real and imaginary parts of a complex number z, use z.real and z.imag.
Use abs() to get the absolute value:
a.real
a.imag
abs(a)
4
5
For additional functions related to complex numbers visit https://docs.python. org/3/library/cmath.html.
Table of Contents
- Preface
- 1. Introduction
- 2. Using Python as a Scientific Calculator
- 3. Drawing, Plotting, and Data Visualization with Matplotlib
- 4. Working with Text Strings
- 5. Variables and Types
- 6. Boolean Values, Functions, Expressions, and Variables
- 7. Lists, Tuples, Dictionaries, and Sets
- 8. Functions
- 9. The ’For’ Loop
- 10. Conditions
- 11. The ’While’ Loop
- 12. Exceptions
- 13. File Operations
- 14. Object-Oriented Programming I – Introduction
- 15. Object-Oriented Programming II – Class Inheritance
- 16. Object-Oriented Programming III – Advanced Aspects
- 17. Recursion
- 18. Decorators
- 19. Selected Advanced Topics