Native Data Types
In Python, all objects have a type>>> x = 1, 2
>>> type(x)
<type 'tuple'>
But for now we will work with Python's existing (i.e., native) types
We have met floats, ints, strings, lists, tuples and bools
Let's review these types, and look a few more
Numeric data types
We have already met ints and floatsHere are a couple more
Long Integers
Typically, anint
is stored with 32 bits of memoryLargest integer is therefore
2**32 / 2 - 1 = 2147483647
You can find the largest
int
on your machine via>>> import sys
>>> sys.maxint
sys.maxint
, Python uses long ints- Size is not limited, but algebraic operations are not as efficient
>>> x = 2**100
>>> x
1267650600228229401496703205376L
>>> type(x)
<type 'long'>
Complex Numbers
Python has a complex data type>>> z = complex(1, 2)
>>> type(z)
<type 'complex'>
>>> z.real, z.imag
(1.0, 2.0)
>>> y = complex(2, 1)
>>> y * z
5j
Strings and String Formatting
String formatting is how we insert variables into a stringHere is a simple method
>>> x, y = 42, 24
>>> string = 'x = ' + str(x) + ' and y = ' + str(y)
>>> print string
x = 42 and y = 24
x = 12.34701
print 'The price increased by %f percent' % x
The price increased by 12.347010 percent
f
stands for floatUse
i
or d
for integer>>> print '%i' % 2
2
>>> print '%d' % 2
2
s
for string>>> print 'this is a %s' % 'string'
this is a string
>>> stock = 'IBM'
>>> change = 10.2
>>> print 'the value of %s changed by %f percent' % (stock, change)
the value of IBM changed by 10.200000 percent
This can be modified. For example:
>>> stock = 'IBM'
>>> change = 10.2
>>> print 'the value of %s changed by %.2f percent' % (stock, change)
the value of IBM changed by 10.20 percent
Dictionaries
One useful native data type we have not met is dictionariesIntroduction
Think of a listX
as a map from 0,...,len(X)-1
to some objectsX = ['gozilla', 21, 'green']
- 0 is mapped to
'godzilla'
X[0] == 'godzilla'
- 1 is mapped to
21
X[1] == 21
- 2 is mapped to
'green'
X[2] == 'green'
>>> d = {'name': 'godzilla', 'age': 21, 'favorite color': 'green'}
>>> d['name']
'godzilla'
>>> d['age']
21
>>> d['favorite color']
'green'
>>> type(d)
<type 'dict'>
The elements 'godzilla', 21 and 'green' are called the values
We can access them as follows:
>>> d.keys()
['age', 'name', 'favorite color']
>>> d.values()
[21, 'godzilla', 'green']
>>> d2 = {1: 'a', 2: 'b'}
>>> d2[1] = 'foo' # Alter the value using the key
>>> d2
{1: 'foo', 2: 'b'}
Keys of a dictionary can be any immutable data type
>>> d2 = {[1, 2]: 'foo'} # This is wrong
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> d2 = {(1, 2): 'foo'} # But this is okay
>>> d = {} # An empty dictionary
>>> d[1] = 'foo'
>>> d
{1: 'foo'}
>>> d[2] = 'bar'
>>> d
{1: 'foo', 2: 'bar'}
>>> X = []
>>> X[0] = 'foo'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
Working with Dictionaries
Often we want to loop through a dictionaryportfolio = {'IBM': 1000,
'COP': 2000,
'IPL': 500}
for k in portfolio.keys():
print "You have %d shares in %s" % (portfolio[k], k)
for k in portfolio:
print "You have %d shares in %s" % (portfolio[k], k)
A useful alternative is to the previous code is
for k, v in portfolio.items():
print "You have %d shares in %s" % (v, k)
items()
method returns the key/value pairs as a listExercises
Problem:Here is a coded message:
coded_message = "Olih#lv#wrr#lpsruwdqw#wr#eh#wdnhq#vhulrxvo|1"
{'#': ' ',
'1': '.',
'O': 'L',
'd': 'a',
'e': 'b',
'h': 'e',
'i': 'f',
'l': 'i',
'n': 'k',
'o': 'l',
'p': 'm',
'q': 'n',
'r': 'o',
's': 'p',
'u': 'r',
'v': 's',
'w': 't',
'x': 'u',
'|': 'y'}
Solution:
coded_message = "Olih#lv#wrr#lpsruwdqw#wr#eh#wdnhq#vhulrxvo|1"
code = {'#': ' ',
'1': '.',
'O': 'L',
'd': 'a',
'e': 'b',
'h': 'e',
'i': 'f',
'l': 'i',
'n': 'k',
'o': 'l',
'p': 'm',
'q': 'n',
'r': 'o',
's': 'p',
'u': 'r',
'v': 's',
'w': 't',
'x': 'u',
'|': 'y'}
decoded_message = ''
for character in coded_message:
decoded_message = decoded_message + code[character]
print decoded_message
0 comments:
Post a Comment