2016 September 14,

CS 111: Type

Whenever you want, you can ask Python about the type of any quantity or variable.

type(7)

type(7.0)

type('7')

type('7.0')

Type is important, because it determines what you can do and what it means. Behold!

y = "123"

y + y

y = 123

y + y

Question 06A: Execute z = 23. After you've done that, what is the type of z, and what is the type of "z"?

To make matters a little more confusing, Python automatically promotes integers to floats in certain circumstances. We've already seen this phenomenon in arithmetic. Here we see it in testing equality.

7 == 7.0

7 == "7"

We arrive at what I call the Golden Rule of Programming: You must know the type of value stored in each variable in your code, or you won't know how to use that variable. Weeks from now, when you call me to your computer to debug your code, I will point at a certain line of code and ask, "What is the type of this variable?" If you cannot answer, then you may be thrown in the Arboretum (or gently encouraged to figure it out).

At this point you might be thinking: "How hard could it be to remember the type of my variables?" Well, when your code gets bigger, you can start to lose track of things. A large program may have millions of variables of many types. So let's practice our mental discipline on small programs first.