缩进
everything is an object
Each object has an associated type (for example, string or function) and internal data.
import
- import random
需要前缀 - from random import *
不需要前缀 - from random import shuffle
不需要前缀, 但只引入了shuffle
注释用#号
Variables and pass-by-reference
When assigning a variable (or name) in Python, you are creating a reference to the object
on the right hand side of the equals sign.
赋值相当于捆绑(指针), 将一个名字和一个对象捆绑起来.
mutable和immutable
1. immutable object can not be modified after creation, functional programming prefers immutable objects.
2. an object of immutable type cannot be changed
In [2]:
a = [1,2,3]
b = a
a.append(4)
b
Out[2]:
[1, 2, 3, 4]
函数传递时需要区分mutable object and immutable object. mutable object会改变对应object的value, 但是immutable不能改变而是新创建一个object, 然后指向过去.
Attributes and methods
- dir(a)
dir(a)
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__getslice__',
'__gt__',
'__hash__',
'__init__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'_formatter_field_name_split',
'_formatter_parser',
'capitalize',
'center',
'count',
'decode',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'index',
'isalnum',
'isalpha',
'isdigit',
'islower',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'partition',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
- 在ipython下 a.< Tab> 可以知道method
isinstance(a,str)
In [9]:
a = 'foo'
isinstance(a,str)
Out[9]:
True
is and ==
只有指向同一对象时, is 才成立
In [10]:
a = [1,2,3]
b = a
c = list(a)
a is b, a is c, a == c
Out[10]:
(True, False, True)
Scalar Type
Numeric types
In [12]:
ival = 6
ival ** 3
Out[12]:
216
In [13]:
3/2, 3/float(2),3//2
Out[13]:
(1, 1.5, 1)
In [14]:
cval = 1+2j
cval*(1-2j)
Out[14]:
(5+0j)
str类型
- 初始化
s = ‘a b c’
s = ”’ a
b
”’ - 不可变
In [17]:
a[9] = 'f'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-a0b130cb4fc3> in <module>()
----> 1 a[9] = 'f'
TypeError: 'str' object does not support item assignment
3.常用操作
In [21]:
a,b,a+b
a = 'hello'
b = 'world'
a,b,a+b
Out[21]:
('hello', 'world', 'helloworld')
- s.replace()
a = 'this is a string'
b = a.replace('string','longer string')
a,b
Out[16]:
('this is a string', 'this is a longer string')
- str
In [18]:
a = 5.6
s = str(a)
a, s
Out[18]:
(5.6, '5.6')
- list
a = 'python'
list(a)
Out[19]:
['p', 'y', 't', 'h', 'o', 'n']
template % (tuple), 例如,template = ‘%.2f %s are worth $%d’, template % (4.5560, ‘Argentine Pesos’, 1)
Booleans
Booleans: True, False
逻辑运算符 and, or , not
#boolean
a = [1,2,3]
if a:
print 'a is not empty'
a is not empty
NoneType
可以用于函数default value
In [25]:
a = None
b = 5
a is None,b is None
Out[25]:
(True, False)
Type Casting
In [23]:
#type casting
a = 3.14
b = str(a)
c = float(b)
[type(x) for x in [a,b,c]]
Out[23]:
[float, str, float]
逻辑运算符, 算数运算符
指数: **
逻辑运算符: and, or , not
一般一个非空对象可以返回ture
其余运算符都正常
control flow
条件语句:
if ...:
elif ...:
else:
循环语句
- For语句
for loops are for iterating over a collection (like a list or tuple) or an iterator. The standard syntax for a for loop is:
for value in collection:
# do something with value
upackged:
for a, b, c in iterator:
# do something
- while 语句
while condition:
#do something
pass 方便debug或者处理无用情况,
if x < 0:
print 'negative!'
elif x == 0:
# TODO: put something smart here
pass
else:
print 'positive!'
Exceptation handling
In [26]:
float("something")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-26-4be67b9718eb> in <module>()
----> 1 float("something")
ValueError: could not convert string to float: something
try/except block:
In [28]:
def attempt_float(x):
try:
return float(x)
except:
return x
attempt_float('1.234'),attempt_float('something')
Out[28]:
(1.234, 'something')
except type
ValueError
In [26]: float("something") -------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-26-4be67b9718eb> in <module>() ----> 1 float("something") ValueError: could not convert string to float: something
TypeError
In [29]: float([1,2]) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-29-382b81e0df55> in <module>() ----> 1 float([1,2]) TypeError: float() argument must be a string or a number
如果我们只想考虑某一部分错误, 那么我们可以在except加错误类型
In [32]:
e
def attempt_float2(x):
try:
return float(x)
except ValueError:
return x
attempt_float2([1,2])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-84767f395991> in <module>()
4 except ValueError:
5 return x
----> 6 attempt_float2([1,2])
<ipython-input-32-84767f395991> in attempt_float2(x)
1 def attempt_float2(x):
2 try:
----> 3 return float(x)
4 except ValueError:
5 return x
TypeError: float() argument must be a string or a number
也可以加入多个类型错误:
In [34]:
def attempt_float3(x):
try:
return float(x)
except (ValueError,TypeError):
return x
attempt_float3([1,2])
Out[34]:
[1, 2]
finally 加入表示是否成功, 都执行的命令
In [35]:
def attempt_float2(x):
try:
return float(x)
except ValueError:
return x
finally:
print 'happy new year!'
attempt_float2([1,2])
Out [35]:
happy new year!
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-35-5b3156c299ff> in <module>()
6 finally:
7 print 'happy new year!'
----> 8 attempt_float2([1,2])
<ipython-input-35-5b3156c299ff> in attempt_float2(x)
1 def attempt_float2(x):
2 try:
----> 3 return float(x)
4 except ValueError:
5 return x
TypeError: float() argument must be a string or a number
range
In [36]:
range(10)
Out[36]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [37]:
range(0,20,2)
Out[37]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]