In [1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from pandas import DataFrame, Series
from numpy.random import randn

In [2]:
a = 'this is a string'
b = 'this is another string'
a + b


Out[2]:
'this is a stringthis is another string'

In [3]:
template = '%.2f %s are worth $%d'
template % (4.5560, 'Argentine Pesos', 1)


Out[3]:
'4.56 Argentine Pesos are worth $1'

In [4]:
template % (3.3333, a + b, 2)


Out[4]:
'3.33 this is a stringthis is another string are worth $2'

In [5]:
True and True


Out[5]:
True

In [6]:
False or True


Out[6]:
True

In [7]:
a = [1, 2, 3]
if a:
    print 'I found something'


I found something

In [8]:
b = []
if not b:
    print 'Empty!'


Empty!

In [9]:
bool([]), bool([1, 2, 3])


Out[9]:
(False, True)

In [10]:
bool('Hello world!'), bool('')


Out[10]:
(True, False)

In [11]:
bool(0), bool(1)


Out[11]:
(False, True)

In [12]:
s = '3.14159'
fval = float(s)
type(fval)


Out[12]:
float

In [13]:
int(fval)


Out[13]:
3

In [14]:
bool(fval)


Out[14]:
True

In [15]:
bool(0)


Out[15]:
False

In [16]:
a = None
a is None


Out[16]:
True

In [17]:
b = 5
b is not None


Out[17]:
True

In [18]:
def add_and_maybe_multiply(a, b, c=None):
    result = a + b
    
    if c is not None:
        result = result * c

    return result

In [20]:
from datetime import datetime, date, time
dt = datetime(2011, 10, 29, 20, 30, 21)

dt.day


Out[20]:
29

In [21]:
dt.minute


Out[21]:
30

In [22]:
dt.date()


Out[22]:
datetime.date(2011, 10, 29)

In [23]:
dt.time()


Out[23]:
datetime.time(20, 30, 21)

In [24]:
dt.strftime('%m/%d/%Y %H:%M')


Out[24]:
'10/29/2011 20:30'

In [25]:
datetime.strptime('20091031', '%Y%m%d')


Out[25]:
datetime.datetime(2009, 10, 31, 0, 0)

In [26]:
dt.replace(minute=0, second=0)


Out[26]:
datetime.datetime(2011, 10, 29, 20, 0)

In [28]:
dt2 = datetime(2011, 11, 15, 22, 30)
delta = dt2 - dt
delta


Out[28]:
datetime.timedelta(17, 7179)

In [29]:
type(delta)


Out[29]:
datetime.timedelta

In [30]:
dt


Out[30]:
datetime.datetime(2011, 10, 29, 20, 30, 21)

In [31]:
dt + delta


Out[31]:
datetime.datetime(2011, 11, 15, 22, 30)

In [32]:
x=-1

In [33]:
if x < 0:
    print 'It"s negative'


It"s negative

In [34]:
def px(x):
    if x < 0:
        print 'It"s negative'
    elif x == 0:
        print 'Equal to zero'
    elif 0 < x < 5:
        print 'Positive but smaller than 5'
    else:
        print 'Positive and larger than or equal to 5'

In [35]:
px(x)


It"s negative

In [36]:
px(3)


Positive but smaller than 5

In [37]:
px(10)


Positive and larger than or equal to 5

In [38]:
px(0)


Equal to zero

In [40]:
a = 5; b = 7
c = 8; d = 4
if a < b or c > d:
    print 'Made it'


Made it

In [41]:
def mysum(seq):
    total = 0
    for value in seq:
        if value is None:
            continue
        total += value
    return total

In [42]:
mysum([1, 2, None, 4, None, 5])


Out[42]:
12

In [44]:
def mysum5(seq):
    total_until_5 = 0
    for value in seq:
        if value == 5:
            break
        total_until_5 += value
    return total_until_5

In [45]:
mysum5([1, 2, 0, 4, 6, 5, 2, 1])


Out[45]:
13

In [46]:
x = 256
total = 0
while x > 0:
    if total > 500:
        break
    total += x
    x = x // 2

In [47]:
total


Out[47]:
504

In [48]:
def f(x, y, z):
    # TODO: 实现这个函数!
    pass

In [49]:
float('1.2345')


Out[49]:
1.2345

In [50]:
float('som')


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-50-b53cdacc4d9a> in <module>()
----> 1 float('som')

ValueError: could not convert string to float: som

In [55]:
def attempt_float(x):
    try:
        return float(x)
    except ValueError:
        return x

In [52]:
attempt_float('1.2345')


Out[52]:
1.2345

In [53]:
attempt_float('som')


Out[53]:
'som'

In [54]:
float(1, 2)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-54-242066800d89> in <module>()
----> 1 float(1, 2)

TypeError: float() takes at most 1 argument (2 given)

In [56]:
attempt_float((1, 2))


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-56-9bdfd730cead> in <module>()
----> 1 attempt_float((1, 2))

<ipython-input-55-84efde0a7059> in attempt_float(x)
      1 def attempt_float(x):
      2     try:
----> 3         return float(x)
      4     except ValueError:
      5         return x

TypeError: float() argument must be a string or a number

In [57]:
def attempt_float(x):
    try:
        return float(x)
    except (TypeError, ValueError):
        return x

In [58]:
f = open('ch13testfinally.txt', 'w')

try:
    f.write("akakakak")
finally:
    f.close()

In [59]:
!cat ch13testfinally.txt


akakakak

In [60]:
f = open('ch13else.txt', 'w')

try:
    f.write('bkbkbkbkbk')
except:
    print 'Failed'
else:
    print 'Succeeded'
finally:
    f.close()


Succeeded

In [61]:
!cat ch13else.txt


bkbkbkbkbk

In [62]:
range(10)


Out[62]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [63]:
range(0, 20, 2)


Out[63]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

In [65]:
val = 0
seq = [1, 2, 3, 4]
for i in range(len(seq)):
    val += seq[i]
val


Out[65]:
10

In [66]:
sum = 0
for i in xrange(10000):
    # %是求模运算符
    if i % 3 == 0 or i % 5 == 0:
        sum += i
sum


Out[66]:
23331668

In [67]:
x = 5
'Non-negative' if x >= 0 else 'Negative'


Out[67]:
'Non-negative'

In [68]:
tup = 4, 5, 6
tup


Out[68]:
(4, 5, 6)

In [69]:
nested_tup = (4, 5, 6), (7, 8)
nested_tup


Out[69]:
((4, 5, 6), (7, 8))

In [70]:
tuple([4, 0, 2])


Out[70]:
(4, 0, 2)

In [72]:
tup = tuple('string')
tup


Out[72]:
('s', 't', 'r', 'i', 'n', 'g')

In [73]:
tup[0]


Out[73]:
's'

In [74]:
tup = tuple(['foo', [1, 2], True])
tup[2] = False


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-74-692985e84db1> in <module>()
      1 tup = tuple(['foo', [1, 2], True])
----> 2 tup[2] = False

TypeError: 'tuple' object does not support item assignment

In [75]:
tup[1].append(3)
tup


Out[75]:
('foo', [1, 2, 3], True)

In [76]:
(4, None, 'foo') + (6, 0) + ('bar',)


Out[76]:
(4, None, 'foo', 6, 0, 'bar')

In [77]:
('foo', 'bar') * 4


Out[77]:
('foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar')

In [78]:
tup = (4, 5, 6)
a, b, c = tup

In [79]:
b


Out[79]:
5

In [80]:
tup = 4, 5, (6, 7)
a, b, (c, d) = tup
d


Out[80]:
7

In [82]:
b, a = a, b
b


Out[82]:
5

In [83]:
seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
for a, b, c in seq:
    pass

In [85]:
a = (1, 2, 2, 2, 3, 4, 2)
a.count(2)


Out[85]:
4

In [88]:
for x in a:
    print str(x) + ','


1,
2,
2,
2,
3,
4,
2,

In [89]:
a_list = [2, 3, 7, None]
tup = ('foo', 'bar', 'baz')
b_list = list(tup)
b_list


Out[89]:
['foo', 'bar', 'baz']

In [90]:
b_list[1] = 'peekaboo'
b_list


Out[90]:
['foo', 'peekaboo', 'baz']

In [91]:
b_list.append('dwarf')
b_list


Out[91]:
['foo', 'peekaboo', 'baz', 'dwarf']

In [95]:
tup + ('x',)


Out[95]:
('foo', 'bar', 'baz', 'x')

In [96]:
b_list.insert(1, 'red')
b_list


Out[96]:
['foo', 'red', 'peekaboo', 'baz', 'dwarf']

In [97]:
b_list.pop(2)


Out[97]:
'peekaboo'

In [98]:
b_list


Out[98]:
['foo', 'red', 'baz', 'dwarf']

In [99]:
b_list.append('foo')
b_list.remove('foo')
b_list


Out[99]:
['red', 'baz', 'dwarf', 'foo']

In [100]:
'dwarf' in b_list


Out[100]:
True

In [102]:
[4, None, 'foo'] + [7, 8, (2, 3)] + ['x']


Out[102]:
[4, None, 'foo', 7, 8, (2, 3), 'x']

In [103]:
x = [4, None, 'foo']
x.extend([7, 8, (2, 3)])


Out[103]:
[4, None, 'foo', 7, 8, (2, 3)]

In [104]:
everything = []
for chunk in [b_list, x]:
    everything.extend(chunk)
everything


Out[104]:
['red', 'baz', 'dwarf', 'foo', 4, None, 'foo', 7, 8, (2, 3)]

In [106]:
everything = []
for chunk in [b_list, x]:
    everything = everything + chunk
everything


Out[106]:
['red', 'baz', 'dwarf', 'foo', 4, None, 'foo', 7, 8, (2, 3)]

In [107]:
a = [7, 2, 5, 1, 3]
a.sort()
a


Out[107]:
[1, 2, 3, 5, 7]

In [108]:
b = ['saw', 'small', 'He', 'foxes', 'six']
b.sort(key=len)
b


Out[108]:
['He', 'saw', 'six', 'small', 'foxes']

In [109]:
import bisect
c = [1, 2, 2, 2, 3, 4, 7]
bisect.bisect(c, 2)


Out[109]:
4

In [110]:
bisect.bisect(c, 5)


Out[110]:
6

In [113]:
bisect.insort(c, 6)
c


Out[113]:
[1, 2, 2, 2, 3, 4, 6, 6, 6, 7]

In [114]:
seq = [7, 2, 3, 7, 5, 6, 0, 1]
seq[1:5]


Out[114]:
[2, 3, 7, 5]

In [116]:
seq[3:4] = [6, 3]
seq


Out[116]:
[7, 2, 3, 6, 3, 3, 5, 6, 0, 1]

In [117]:
seq[:5]


Out[117]:
[7, 2, 3, 6, 3]

In [118]:
seq[3:]


Out[118]:
[6, 3, 3, 5, 6, 0, 1]

In [119]:
seq[-4:]


Out[119]:
[5, 6, 0, 1]

In [120]:
seq[-6:-2]


Out[120]:
[3, 3, 5, 6]

In [121]:
seq[::2]


Out[121]:
[7, 3, 3, 5, 0]

In [122]:
seq[::-1]


Out[122]:
[1, 0, 6, 5, 3, 3, 6, 3, 2, 7]

In [123]:
for i, value in enumerate(seq):
    print i, value


0 7
1 2
2 3
3 6
4 3
5 3
6 5
7 6
8 0
9 1

In [124]:
some_list = ['foo', 'bar', 'baz']
mapping = dict((v, i) for i, v in enumerate(some_list))
mapping


Out[124]:
{'bar': 1, 'baz': 2, 'foo': 0}

In [ ]: