Integers and Floats

In Python, there are two main types of numbers: integers and floats. The main difference between them is that a float is a number with a decimal point, whereas an integer is a number without a decimal point.


```python
# Integers and floats (more precise)
var_int = 12
var_float = 12.0001


The floats are represented in decimal system (base-10), whereas the machine uses binary system (base-2). This means that the machine has to approximate the float value to a binary value. This can lead to some approximation errors. For example, the decimal number 0.1 is represented in binary as an infinite sequence of 0 and 1. The machine will approximate it to a finite sequence of 0 and 1, which will lead to an approximation error. Be aware of this tolerance when you use floats in your script.


Math operators


Floats and integers can be use with math operators.

# Addition and substraction
print(0.5 + 0.3)
print(10 - 3)

# Division
print(4/3)

# Multiplication and exponent
print(5 * 5)
print(5 ** 5)

# Modulus
print(9 % 3) # = 0
print(9 % 4) # = 1


Converting


It is possible to convert a float to an integer and vice-versa. Why would you do that? Well, sometimes you need more precision (float) and sometimes you need less (integer). It is also possible to convert a string to an integer or a float.

# Convert float to integer
print(int(0.5))

# Convert integer to float
print(float(5))

# Convert string to integer
print(int("5"))

# Convert string to float
print(float("5.5"))


🛠 Exercises


01: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 04: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍

Solutions:

01: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 04: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍