Lesson A2 – Working with numbers

Let’s try to put Python to some practical use. The possibilities you have with this general purpose language are huge, but at the very least, we can use the Python interpreter as a fancy pocket-calculator. You can find what we talk about here also in different form in the official Python beginners-tutorial.

Types of numbers

Numbers can be represented in Python by the data types:

  • int (whole numbers)

  • float (floating point numbers)

  • complex (complex numbers)

We can access the type of a number by using the function type.

[1]:
# integer
i = 1
print(type(i))
<class 'int'>
[2]:
# floating point number
f = 0.5
print(type(f))
<class 'float'>

Trailing zeros in floats can be omitted. You can also store a whole number as a float by explicit use of a decimal point.

[3]:
# whole number as floating point number
f = 1.
print(type(f))
<class 'float'>

To create a complex number we can make a number imaginary by using the letter j.

[4]:
# complex number
c = 2 + 6j
print(type(c))
<class 'complex'>

You can get the real and the imaginary part separately, where both parts are considered floats.

[5]:
print(c.real, type(c.real))
print(c.imag, type(c.imag))
2.0 <class 'float'>
6.0 <class 'float'>

Operations with numbers

In Python, you can use the operators +, -, *, and / to combine objects. For numbers, these behave like you would expect it from arithmetic operators.

[6]:
# Add/Substract numbers
print(1 + 1)
print(1 - 1)
2
0
[7]:
# Multiply/divide numbers
print(1 * 2)
print(2 / 2)
2
1.0

Note, that Python automatically returns a float when we divide an integer by another.

[8]:
print(type(2 / 2))
<class 'float'>

You can explicitly use integer division, in which case the result will be floored (rounded down) to the next lower integer.

[9]:
print(3 // 2, type(3 // 2))
1 <class 'int'>

Furthermore, there is the % operator (the modulo operator) that gives you the rest of an integer division.

[10]:
print(3 % 2, type(3 % 2))
1 <class 'int'>

When we mix integers with floats, Python treats both numbers as floats, which is the broader number definition. You can say float is a wider type than int.

[11]:
print(1 + 1., type(1 + 1.))
2.0 <class 'float'>

Similarly, we get a complex number when we combine floats and complex numbers.

[12]:
print(1. + (1 + 1j), type(1. + (1 + 1j)))
(2+1j) <class 'complex'>

This even works when the imaginary part of the number is zero.

[13]:
print(1.0 + (1 + 0j), type(1.0 + (1 + 0j)))
(2+0j) <class 'complex'>

Raising a number to a higher power can be done in two ways.

[14]:
print(2 ** 3)
print(pow(2, 3))
8
8

With these basic operations you can now solve simple equations, e.g. you can compute the Coulomb repulsion of two positive elemental charges at a given distance. Python understands floating point numbers in scientific notation: \(1\mathrm{e}2 = 1 \times 10^2\).

[15]:
r = 1e-9             # m = 1 nm,  Distance
ke = 9e9             # N * m**2 * C**−2,  Force constant in vacuum
q1 = q2 = 1.602e-19  # C,  Charges

F = (ke * q1 * q2) /  r**2  # Calculate force
print("Coulomb interaction: ", F, "N")
Coulomb interaction:  2.3097635999999995e-10 N

Advanced topics

Special values

The probably most frequently used number type for computations is float. It is the type of choice to represent real numbers. Besides actual real numbers Python knows a few special numbers that are not really numbers.

[16]:
no_number = float('nan')  # Python representation of "not-a-number"
type(no_number)
[16]:
float
[17]:
print(no_number + 1)
# Acts as a placeholder that can be used in computations
nan
[18]:
inf = float('inf')  # Python representation of infinity
type(inf)
[18]:
float
[19]:
minf = float('-infinity')  # Python representation of -infinity
type(minf)
[19]:
float
[20]:
print(inf + 1)
# Can be used in computations
inf
[21]:
print(inf + minf)
# Can be used in computations
nan

Type conversion

To force a number to be of a certain type we can use

  • int()

  • float()

  • complex()

[22]:
print(type(int(2.1)))
<class 'int'>

But this is not always possible…

[23]:
print(type(int(2 + 6j)))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-8c34586a16f6> in <module>
----> 1 print(type(int(2 + 6j)))

TypeError: can't convert complex to int

We are getting another type of error here. A TypeError occurs when you try to do something with an object that is not permitted by its type.

It is always possible to convert a number into a str using str(). If a string happens to be actually a number, it can also converted using the above functions.

[24]:
print(str(10.1))
10.1
[25]:
print(int("10"))
10
[26]:
print(int("10.1"))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-26-bc0afe9b1b1a> in <module>
----> 1 print(int("10.1"))

ValueError: invalid literal for int() with base 10: '10.1'