Unit A Reading assignment - variables

Chapter 2 Py Ingredients: Numbers, Strings, and Variables

Notes on variables and data

The book's discussion of Python variables on page 19 (in the 2nd edition) is crucial to an understanding of Python. In languages like C++, you must explicitily define the type of a variable. By contrast, Python variables are not explicitly typed. Instead, a variable is an untyped reference to an object which itself is strongly typed. So, both C++ and Python are strongly typed languages, but are implemented in different ways.

As the book points out, a variable is simply a name that is a reference to a object containing some sort of data. The nature of the referenced object determines the type of the object. Note that the type is associated with the underlying referenced object and not the variable. This means that the same variable can be used to reference any type of object.

We can use the built-in function type to see an example of Python typing:

x = 42
print("Type of object referenced by x when x = 42 is", type(x))
x = 'Hello world'
print("Type of object referenced by x when x = 'Hello world' is", type(x))

Output is:

Type of object referenced by x when x = 42 is <class 'int'>
Type of object referenced by x when x = 'Hello world' is <class 'str'>

For additional in-depth explanation, see:

http://www.voidspace.org.uk/python/articles/duck_typing.shtml

return