Exercise 1

Assign three variables, called myinteger, myfloat, and mystring with the values 3, 5, and "ten" with the types int, float, and string respectively.


In [ ]:


In [ ]:
print myinteger
print myfloat
print mystring

Confirm that the types are int, float, and string by running the following expressions.


In [ ]:
print type(myinteger) == int
print type(myfloat) == float
print type(mystring) == str

Exercise 2

The operations * and + are defined for some combinations of data types, but not for others. Determine which of these operations gives an error. Any surprises?


In [ ]:
myint * myfloat

int * string :


In [ ]:

float * string :


In [ ]:

string + float :


In [ ]:

string + string :


In [ ]:

Exercise 3

  1. Assign the string thethreeitems the value of "3, 5, and ten" using the contents of the three variables defined above ( myinteger, myfloat, and mystring) (Hint: You need to get everything into the str data type. You may need to coerce some data types.)

In [ ]:
thethreeitems =

Test your work:


In [ ]:
print thethreeitems == "3, 5, and ten"

Exercise 4

len() is a builtin function to count the length of things, particularly lists and strings. Find the length of thethreeitems, and determine whether it is the length or the length -1.


In [ ]:

Example 5

Python lists are agnostic to the type of the data contained within them. You can generate arrays with different elements of different types:


In [ ]:
pythonlist =[2.43, 1, 0.92, 0, "0.38"]

print pythonlist

In [ ]:
print type(pythonlist[0]), type(pythonlist[1]), type(pythonlist[2]), type(pythonlist[3]), type(pythonlist[4])

numpy is an extremely useful library that has its own data types; you will frequently need to specify the types as float or possibly higher-precision float at the time you create them. The numpy data types are only sometimes compatible with the native data types.


In [ ]:
import numpy as np
numpyarray = np.array(pythonlist)
print numpyarray

numpy requires that all of the elements in its array are homogeneous, that is, they have to have the same type. What is the default data type of a after the conversion?


In [ ]:
type(numpyarray[0])

Ack! The results of type() do not portray the representation. For that we need


In [ ]:
print numpyarray.dtype

Which is not a numeric data type. We can cause it to be stored as numpy floats if we specify float when we convert it to numpy:


In [ ]:
numpyfloatarray = np.array(pythonlist, dtype="float")

Exercise 5

Write an expression to determine the number of digits in a non-negative integer. Hint: maybe len() or math.log() might be useful here.


In [ ]:
len(str(int(45)))

Test your expression on 45, 2, and 2.0. Does it work for all three?


In [ ]: