Marquette University, view of Wisconsin Avenue  

Module 2

Variables and Types

Python stores values and more complicated things as "objects". You can think of an object as a set of values stored at a specific memory location. With current computer technology, these values are a bit pattern of various length, whose value is calculated according to the character of the object, namely the "type".

The most important built-in types are integers (int), floating point numbers (float), and strings (str). We can take an object of a certain type and change it to a different object using casting. The casts considered are int, float, and str.

Objects can have names. You should think of objects as "boxes" and names as "label" that you can put on a box. The same box can have multiple labels. If we operate on a box, its contents will change. If we have several names (labels) for the same object (box), then using any name will allow us to change the contents of the box, and if we then access the box through a different label, we will see the contents changed. You can also take a label and put it on a different box. For example, if you say


x = 3 
x = "abc"

then we have two objects (boxes) and one name (label). The first line creates an object with value 3 (and therefore of type int) and attaches the name x to it, the second line creates a new object with value "abc" and then attaches the same name to it. Incidentally, the first object becomes inaccessible and a background process will remove ("free") the object.

Expressions are built from objects and operators. The order of operators is specified by a built-in precedence (power before multiplication / division before addition / subtraction) and round parentheses. Other than the necessity to use * for multiplication and / for division, expressions use almost the same syntax used in Mathematics for numerical types. Operators can use the same symbol for different operations, the exact operation meant by a symbol also depends on the types of the variables.

In this lesson, we see the first programming paradigm. We can use input("prompt") to obtain input from the shell, then cast the result to a numeric type (int or more typically float), change the result according to a formula, and finally print out the result. This is a simple application used to change measure. Here is the Celsius to Fahrenheit translator:


inp = input("Enter the temperature in Celsius: ")
celsius = float(inp)
fahrenheit = 9*celsius/5+32
print("The temperature is", fahrenheit, "Fahrenheit.")
This code can be streamlined, e.g. by applying the cast directly to the result of input instead of using a temporary variable. In fact, you can write the whole program in a single statement, but it becomes less readable:

print("The temperature is", 9*float(input("Enter the temperature in Celsius: "))/5+32, "Fahrenheit.")
This is really going too far!