To programmers who only program using Python, it would seem odd that a particular variable could have only one type and that it would have to be initially defined to have that type, but it is true. In Python, the type associated with a variable can change. For example, consider the statements:
x = 10 # X is an integer
x = x*0.1 # X is floating point now
x = (x*10 == 10) # X is Boolean
Some find this perfectly logical, and others find it confusing. As the variable is used according to its current type, all will be well.
Even simple Python types can be complex in terms of their implementation. A programmer rarely needs to know about the underlying details of types like integers. In many programming languages, an integer is simply a one- or two- word number, and the languages build operations like + from the instruction set of the computer. If, for example, a one-word integer A is added to another one B, it can be done using a single computer instruction like ADD A, B. This is very fast at execution time.
Python was designed to be convenient for the programmer, not fast. An integer is actually a complex object that has attributes and operations. This will become clearer as more Python examples are written and understood, but as a simple case, think about the way that C++ represents an integer. It is a 32-bit (4 byte) memory location, which is a fixed size space in memory. The largest number that can be stored there is 232-1. Is that true in Python?
Here’s a program that will answer that question, although it uses more advanced features:
for i in range (0,65):
print (i, 2**i)
Even an especially long integer is less than 65 bits. This program runs successfully and quickly. Integers in Python have an arbitrarily large size. Calculating 264 * 264 is possible and results in 340282366920938463463374607431768211 456. This is very handy indeed from a programmer’s perspective.
The type of a variable can be determined by the programmer as the program executes. The function type () returns the type of its parameter as a string, and it can be printed or tested. So, the code
z = 1
z = 1.0
will result in
If one needed to know if z was a float at a particular moment, then
if type(z)is float:
would do the trick. Type(z) does not return a string, it returns a type. The print () function recognizes that and prints a string, just as it does for True and False. So
if type(z) == “<class ‘float’>”:
would be incorrect.
In future chapters, this malleability of types will be further described, and practical methods for taking advantage of it in Python will be examined.
Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.