Types

CS 65: Introduction to Computer Science I

Values we've seen so far

So far, we've seen different kinds of data

In [2]:
num_students = 42 #whole numbers
avg_gas_estimate = 2.70 #numbers with decimal
print("Hello world!") #text data
Hello world!

All data has a type which defines what kind of thing it is and what you can do with it.

Names of some types

integer: whole numbers

floating point: numbers with decimal points

string: text data

The type() function can be used to tell you what kind of type something is.

Both values and variables can have types.

In [1]:
type(2.70)
Out[1]:
float
In [3]:
type(avg_gas_estimate)
Out[3]:
float
In [4]:
type("Hello world")
Out[4]:
str
In [5]:
type(num_students)
Out[5]:
int

Expressions on strings

We've seen how arithmetic operators work on numerical types like ints and floats.

Strings have their own operators too - and some look like arithmetic operators!

In [6]:
greeting = "Hello"
name = "Eric"
greeting+name
Out[6]:
'HelloEric'
In [7]:
greeting-name #not allowed
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-ea5c4b3c4eb7> in <module>
----> 1 greeting-name #not allowed

TypeError: unsupported operand type(s) for -: 'str' and 'str'

Can't apply all string operations to numbers

Similarly, you can't do everything with numbers that you can with strings.

In [8]:
len(name)
Out[8]:
4
In [9]:
len(num_students)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-5c4b8b950dfb> in <module>
----> 1 len(num_students)

TypeError: object of type 'int' has no len()

Other types we'll see

There are several other built-in types that we'll hear more about later like

Boolean: can have value True or False

List: for keeping track of a sequence of values

In [10]:
type(False)
Out[10]:
bool
In [11]:
type([1,2,3])
Out[11]:
list

You can even make your own types or use those that others have created.