Numbers and using Python as a calculator#

Integer values#

You can simply type numbers in a jupyter notebook cell. Executing it let’s the attached Python interpreter read the cell content and execute it as source code provided. In this case the integer number 1 gets evaluated. It’s result is rather unsurprinsingly just the value 1.

1
1

The type of this number is int. You can retrieve the type of any Python object using the type function, which is one of a small number of builtin functions, which are always available for use right after the Python interpreter has started.

type(1)
int

All expected basic operations are possible using integer numbers, such as addition, subtraction, multiplying and division.

1 + 1
2
1 - 2
-1
2 * 2
4
2 / 3
0.6666666666666666

Divisions are special though as the result of a division operation may change the data type. In the former case the result is no longer an integer value, but a floating point type one. To keep the result an integer value use the integer division operator //.

2 // 3
0

Also building the power of two values is available as a builtin. The operator for this is a double asterisk **.

2**2
4

A rather special, yet useful operator is the modulo operator, which shows the remainder of a division. The operator symbol is the percent symbol %.

3 % 2
1

To retrieve both the result of an integer division along with its remainder another builtin function can be used. The operator for this is divmod.

divmod(5, 2)
(2, 1)

The accuracy for integer arithmetics is not limited in Python. Special algorithms exist, which help to address calculations with very large numbers, which usually do not fit into a variable for integer types for the specicic machine the Python interpreter is running on. In those cases the calculations are split into iterative operations leading to a valid final result. As a result the limitation for doing integer based math operations is more related to available cpu performance and memory than the size of the datatype used.

2**10
1024
2**20
1048576
2**30
1073741824
2**40
1099511627776
2**100
1267650600228229401496703205376
2**1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
2**10_000
19950631168807583848837421626835850838234968318861924548520089498529438830221946631919961684036194597899331129423209124271556491349413781117593785932096323957855730046793794526765246551266059895520550086918193311542508608460618104685509074866089624888090489894838009253941633257850621568309473902556912388065225096643874441046759871626985453222868538161694315775629640762836880760732228535091641476183956381458969463899410840960536267821064621427333394036525565649530603142680234969400335934316651459297773279665775606172582031407994198179607378245683762280037302885487251900834464581454650557929601414833921615734588139257095379769119277800826957735674444123062018757836325502728323789270710373802866393031428133241401624195671690574061419654342324638801248856147305207431992259611796250130992860241708340807605932320161268492288496255841312844061536738951487114256315111089745514203313820202931640957596464756010405845841566072044962867016515061920631004186422275908670900574606417856951911456055068251250406007519842261898059237118054444788072906395242548339221982707404473162376760846613033778706039803413197133493654622700563169937455508241780972810983291314403571877524768509857276937926433221599399876886660808368837838027643282775172273657572744784112294389733810861607423253291974813120197604178281965697475898164531258434135959862784130128185406283476649088690521047580882615823961985770122407044330583075869039319604603404973156583208672105913300903752823415539745394397715257455290510212310947321610753474825740775273986348298498340756937955646638621874569499279016572103701364433135817214311791398222983845847334440270964182851005072927748364550578634501100852987812389473928699540834346158807043959118985815145779177143619698728131459483783202081474982171858011389071228250905826817436220577475921417653715687725614904582904992461028630081535583308130101987675856234343538955409175623400844887526162643568648833519463720377293240094456246923254350400678027273837755376406726898636241037491410966718557050759098100246789880178271925953381282421954028302759408448955014676668389697996886241636313376393903373455801407636741877711055384225739499110186468219696581651485130494222369947714763069155468217682876200362777257723781365331611196811280792669481887201298643660768551639860534602297871557517947385246369446923087894265948217008051120322365496288169035739121368338393591756418733850510970271613915439590991598154654417336311656936031122249937969999226781732358023111862644575299135758175008199839236284615249881088960232244362173771618086357015468484058622329792853875623486556440536962622018963571028812361567512543338303270029097668650568557157505516727518899194129711337690149916181315171544007728650573189557450920330185304847113818315407324053319038462084036421763703911550639789000742853672196280903477974533320468368795868580237952218629120080742819551317948157624448298518461509704888027274721574688131594750409732115080498190455803416826949787141316063210686391511681774304792596709376
2**100_000
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
File /opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/IPython/core/formatters.py:711, in PlainTextFormatter.__call__(self, obj)
    704 stream = StringIO()
    705 printer = pretty.RepresentationPrinter(stream, self.verbose,
    706     self.max_width, self.newline,
    707     max_seq_length=self.max_seq_length,
    708     singleton_pprinters=self.singleton_printers,
    709     type_pprinters=self.type_printers,
    710     deferred_pprinters=self.deferred_printers)
--> 711 printer.pretty(obj)
    712 printer.flush()
    713 return stream.getvalue()

File /opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/IPython/lib/pretty.py:394, in RepresentationPrinter.pretty(self, obj)
    391 for cls in _get_mro(obj_class):
    392     if cls in self.type_pprinters:
    393         # printer registered in self.type_pprinters
--> 394         return self.type_pprinters[cls](obj, self, cycle)
    395     else:
    396         # deferred printer
    397         printer = self._in_deferred_types(cls)

File /opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/IPython/lib/pretty.py:779, in _repr_pprint(obj, p, cycle)
    777 """A pprint that just redirects to the normal repr function."""
    778 # Find newlines and replace them with p.break_()
--> 779 output = repr(obj)
    780 lines = output.splitlines()
    781 with p.group():

ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit

and so forth.

Note

For better readability Python allows for inserting an underscore _ as a sepator to group digits. The position of the underscore is not defined and can be arbitrarily chosen to match the circumstances. For integer values grouping to match thousands is very common and supports readability quite a bit. E.g. 1_000_000_000 is much more readable than 1000000000.

All values can be expressed in different number systems, such as hexadecimal, octal or binary.

In the following all number representations define the same value, which is 10.

10
10
0b1010
10
0xa
10
0o12
10

Floating point arithmetics#

Floating point numbers are represented by the float type. Each number containing a dot makes the number a float in Python. Leading and trailing zeros are considered optional here. They may be used for readability reasons, but do not change the internal representation.

The following three variants of writing out the number 0.10 are all the same thing for Python.

0.1
0.1
.1
0.1
0.10
0.1

Again the type of a value can be retrieved using the type builtin function.

type(.1)
float

All the same basic math operations exist for floating point values as well. Let’s quickly check the ones we’ve just used for integer values.

Addtion:

1. + 2.1
3.1

Subtraction:

1. - 2.1
-1.1

Multiplication:

1. * 2.2
2.2

Division:

1. / 2.2
0.45454545454545453

Power:

2. ** .5
1.4142135623730951

Modulo:

5. % 2.1
0.7999999999999998

Divmod:

divmod(5. , 2.1)
(2.0, 0.7999999999999998)

Note

All number types can be happily mixed when doing calculations in your code. Python will make sure to choose an appropriate datatype for the result offering the best accuracy possible.

Complex numbers#

To complete the collections of number types in Python, there is another one for complex numbers. They consist of a real and imaginary part which are simply added to create the complex number. The imaginary part is denoted with the letter j in this case.

1 + 2j
(1+2j)

Helper functions in the math module#

When it comes to more sophisticated math operations the builtin functions are possibly no longer enough. We need the help of our first Python module to proceed. We can simply import such a module into our current namespace. By doing so the functionality provided by the module becomes available for use. A few options exist for the syntax to import functionality of a module.

We can import all available functions from a module. from math import *

This is technically correct, however it should never be used, as it will completely clutter our namespace and possibly overwrite existing functions havin the same name.

If it is clear that just one or a few functions need to be used, they can be explicitely stated in the import statement. from math import sin, cos, tan

Or, if it is unclear how many functions will be necessary, or the namespace should be kept very explicit, then just the module can be imported. import math

The trigonometric functions sin, cos and tan can be used as math.sin, math.cos and math.tan in that case.

There are more options for importing functions from modules, and we will cover them later, but these are the most commonly used variants.

So let’s play with those a little.

import math

Once the module is imported you can use the builtin method dir to see what the module has to offer. This will list all available objects in the module, being it functions or variables. Let’s have a look.

dir(math)
['__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'acos',
 'acosh',
 'asin',
 'asinh',
 'atan',
 'atan2',
 'atanh',
 'cbrt',
 'ceil',
 'comb',
 'copysign',
 'cos',
 'cosh',
 'degrees',
 'dist',
 'e',
 'erf',
 'erfc',
 'exp',
 'exp2',
 'expm1',
 'fabs',
 'factorial',
 'floor',
 'fmod',
 'frexp',
 'fsum',
 'gamma',
 'gcd',
 'hypot',
 'inf',
 'isclose',
 'isfinite',
 'isinf',
 'isnan',
 'isqrt',
 'lcm',
 'ldexp',
 'lgamma',
 'log',
 'log10',
 'log1p',
 'log2',
 'modf',
 'nan',
 'nextafter',
 'perm',
 'pi',
 'pow',
 'prod',
 'radians',
 'remainder',
 'sin',
 'sinh',
 'sqrt',
 'tan',
 'tanh',
 'tau',
 'trunc',
 'ulp']

You can see the trigonometric functions already mentioned above, but also some variables or constants, having the value of $\pi$ at hand.

math.sin(math.pi / 2.), math.cos(0)
(1.0, 1.0)