Skip to content

Integers & Floats

Integers

Python treats numbers in several different ways, depending on how they are used. Let’s first look at how Python manages whole numbers called integers (int).

Any number without decimal places is automatically interpreted as an integer.

number = 10176

We can verify the type of the variable number with type().

number = 10176
print(type(number))
>>> Output
<class 'int'>

Arithmetic operators

Of course, with integers, you can perform basic arithmetic operations. These are:

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
** Exponentiation
% Modulo (Used to calculate the remainder of a division)
// Floor division
# Modulo
20 % 3
>>> Output
2
# Floor division
20 // 3
>>> Output
6
Info

The floor division // is often referred to as integer division. It rounds down to the nearest whole number.

Integer division
20 // 3
>>> Output
6

Contrary, the divison operator / does not round the result.

Float division
20 / 3
>>> Output
6.666666666666667

Hence, / is referred to as float division as it always returns a float (a number with decimal places). More on floats in a second.

Moreover, you can use multiple operations in one expression. You can also use parentheses to modify the order of operations so Python can evaluate your expression in the order you specify. For example:

2 + 3 * 4
>>> Output
14
(2 + 3) * 4
>>> Output
20

Floats

Any number with decimal places is automatically interpreted as a float.

number = 10176.0
print(type(number))
>>> Output
<class 'float'>

All previously introduced arithmetic operations can be used for floats as well.

3.0 + 4.5
# operations with floats and integers
3.0 * (4 / 2)

Limitations

Info

Floats are not 100% precise. "[...] In general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine." (The Python Tutorial, 2024)1

So be aware that these small numerical errors could add up in complex calculations.

34.3 + 56.4

... results in

>>> Output
90.69999999999999
Calculate the BEP

Use variables and arithmetic operations to calculate the break-even point (the number of units that need to be sold to cover the costs) for a product. The break-even point is given as:

\[ \text{BEP (units)} = \frac{\text{Fixed Costs}}{\text{Price per Unit} - \text{Variable Cost per Unit}} \]

Calculate the \(\text{BEP}\) for the following values:

  • Fixed Costs: 30000
  • Variable Cost per Unit: 45
  • Price per Unit: 75

Assign each given value to a variable. Print the result in a sentence, e.g. "The break-even point is X units."

Recap

This section was all about numbers in Python. We have covered:

  • Whole numbers int
  • Decimal numbers float
  • Floating-point arithmetic issues and limitations

Next up, we will introduce the bool and NoneType type in Python.