程序输入与输出¶
打印字符串¶
In [1]:
myString = "hello word"
print myString
格式化字符串¶
In [7]:
print "%s is number %d!"%("python",1)
print "{} is number {}!".format("python",2) #python官方推荐
重定向¶
In [12]:
import sys
print >> sys.stderr,"write to standard error"
logfile = open('./deleteme.txt','wb')
print >> logfile, "write to deleteme.txt"
logfile.close()
交互式输入¶
In [15]:
username = raw_input('enter your name:')
In [16]:
username #输出值都是字符串
Out[16]:
print的小tip¶
带都好的print语句输出的元素之间会自动添加一个空格¶
In [17]:
print 'hello', 'world'
print会在最后添加一个换行符¶
In [19]:
for c in 'hello':
print c
print最后增加一个都好,会抑制换行符¶
In [20]:
for c in 'hello':
print c,
注释¶
普通注释¶
In [21]:
# one comment
文档注释¶
In [22]:
def func():
"this is doc string"
操作符¶
In [24]:
print -1*3+2**3+1/3
print 2**3
In [26]:
print long(10),float(10),bool(10),complex(10)
字符串¶
In [29]:
print 'a"b"'
In [30]:
print "a'b'"
In [31]:
print '''a
b
c'''
索引与切片¶
In [28]:
astring = 'python'
print astring[0]
print astring[1:2]
print astring[:2]
print astring[2:]
print astring[-1]
print astring + 'is cool'
print astring * 2
In [33]:
alist = ['jack',3,1.0]
alist
Out[33]:
In [34]:
atuple = ('rose',1,3.0)
atuple
Out[34]:
In [37]:
adict = {'hose':'baidu','port':80}
print adict
print adict.keys()
for key,value in adict.items():
print key,value
In [38]:
print alist
In [40]:
aset = set(alist)
print aset
bset = set([3.5,'jack'])
print aset.intersection(bset) #交集
print aset.difference(bset) #并集
enumerate返回元素本身和id¶
for else¶
In [42]:
for i in range(0,1):
if i==2:
print 1
else:
print 0
列表解析(列表推导)¶
In [43]:
cube = [x**3 for x in range(4)]
cube
Out[43]:
In [44]:
cube = [x**3 for x in range(4) if not x%2]
cube
Out[44]:
字典也可以¶
In [48]:
adict = {'one':1,'two':2}
cube = {key+'_cube':value**3 for key,value in adict.items()}
cube
Out[48]:
函数¶
In [49]:
def add(x,y=1):
return x+y
In [50]:
add(3)
Out[50]:
In [70]:
class FooClase(object):
version = 0.1
def __init__(self, name='no name'):
self.name = name
print 'create a class instance for'
def showname(self):
print 'your name is', self.name
print 'myname is', self.__class__.__name__
def showver(self):
print self.version
def addMe(self, x):
return x + x
In [72]:
folo1 = FooClase()
folo1.showname()
In [74]:
folo1.showver()
In [75]:
print folo1.addMe(5)
实用函数¶
help(obj) 在线帮助, obj可是任何类型
callable(obj) 查看一个obj是不是可以像函数一样调用
repr(obj) 得到obj的表示字符串,可以利用这个字符串eval重建该对象的一个拷贝
eval_r(str) 表示合法的python表达式,返回这个表达式
dir(obj) 查看obj的name space中可见的name
hasattr(obj,name) 查看一个obj的name space中是否有name
getattr(obj,name) 得到一个obj的name space中的一个name
setattr(obj,name,value) 为一个obj的name space中的一个name指向vale这个object
delattr(obj,name) 从obj的name space中删除一个name
vars(obj) 返回一个object的name space。用dictionary表示
locals() 返回一个局部name space,用dictionary表示
globals() 返回一个全局name space,用dictionary表示
type(obj) 查看一个obj的类型
isinstance(obj,cls) 查看obj是不是cls的instance
issubclass(subcls,supcls) 查看subcls是不是supcls的子类