Python Data Types

= Data Types =

Each variable in python has a specific data type, which tells the computer what is contained within the variable. Python automatically figures out the type of a variable and updates it as needed based on your code.

The primitive (most basic) data types in python are:

Python also has types that contain other types, called containers:

Every class also counts as its own type. If class  inherits from class , then an object of class   is considered to have a type of both   and.

Why are there two different types for numbers?

At first, it may seem like floats are better than ints, since they can store decimals and ints can’t (and indeed, languages such as javascript only use floats). However, the trade-off is that floating-point numbers aren’t perfectly precise. For example, if you take a very large number, such as  and add , it won’t do anything, since there is not enough precision left to store the one-tenth. In practice, the difference doesn’t matter that much, and you should usually let python decide which to use unless you know that a number shouldn’t have a decimal point. = Type Conversion =

You can convert one type into another by calling the function with the same name as the type:

= Type Hinting =

It’s easy to make mistakes when you think something is one type when it’s actually a different type. Consider this code:

This code will run with no errors. But did you catch the mistake? If we run it, it prints  instead of. The problem is that we never actually called the function, so instead of setting  to its result, we set   to the function itself. However, there is a way to catch errors like this, by telling the computer what data type a variable should be. You write type hints after a variable by adding a colon and then the type. Here, we can add a type hint for the variable  on line 4:

Unfortunately, this code will still run, and will result in the same output. But if your code editor is set up to do so, it will point out the error before you even run the code:

Expression of type &quot; -&gt; Literal[5]&quot; cannot be assigned to declared type &quot;int&quot; [Ln 4] &quot;object&quot; is incompatible with &quot;int&quot; What this error means is that we said that  is an , but we actually set it to a function (  means “a function that takes no arguments and returns the number 5”).

Why don’t I see any errors?

This won’t work in Thonny, since it doesn’t have support for type checking. To use it, you will need to use an editor such as VSCode or Visual Studio (guide). You also need to make sure that you have enabled type checking in the settings. In python, type hinting is completely optional, but in other programming languages, such as C++, you always have to tell the computer a variable’s data type yourself. While it is extra work, it helps you avoid mistakes, and can make your code run faster.