- Author:杜七
一、条件、循环和其他语句
1)寻找100以内最大平方数
from math import sqrt
for n in range(99,0,-1):
root = sqrt(n)
if root = int(root):
print n
break
else:
print 'Don's find it!'
2)处理一个word
word = 'newyear'
while word:
word = raw_input('Please enter a word:')
print 'the word was' + word
3)轻量级循环-List
[x*x for x in range(10)]
[x*x for x in range(10) if x %3 ==0]
[x*x for x in range(10) for x in range(5)]
4)使用exec和eval执行和求值字符串
exec "print 'hello world!'"
eval(raw_input("enter an arithmetic expression:"))
enter an arithmetic expression: 6 + 12 * 2
30
5)读写文件
f = open(r'd:\test.txt','r')
print f.read()
f.close()
f = open(r'd:\test.txt','a')
f.write('add a line')
f.close()
f = open(r'd:\test.txt','r')
lines = f.readlines()
for line in lines:
print line
二、抽象、递归和类
1)收集参数
def print_params(title,*params):
print title
print params
print_params('Params:',1,2,3)
Params:
(1,2,3)
参数前的星号把其他参数收集起来元组返回,这个对于关键字参数print_params(title,x=2)不适用。
def print_params2(**params):
print params
>>> print_params2(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3}
2)递归
def power(x,n):
if n == 0:
return 1
else:
return x*power(x,n-1)
3)对象
- a>多态
- b>封装
- c>继承
创建一个自己的类:
__metaclass__ = type # 确定使用新式类
class Person:
def setName(self,name):
self.name = name
def getName(self):
return self.name
def greet(self):
print "Hello,world!I'm %s." % self.name
>>> boo = Person()
>>> boo.setName('duqi')
>>> boo.getName()
'duqi'
>>> boo.greet()
Hello,world!I'm duqi.
继承,如下:
class SPAMPerson(Person):
def setName(self,First,Second):
self.First=First
self.Second = Second
>>> issubclass(SPAMPerson,Person) # 通过issubclass判断是否之类
True
>>> person = SPAMPerson()
>>> person.setName('du','qi')
>>> person.First
'du'
>>> person.Second
'qi'
三、模块和标准库、异常
1)模块
UNIX系统中,通过sys.path.expanduser('~/python') 告诉Python去哪找自己编写的模块
# 查看某个模块的功能函数
[n for n in dir(module) if not n.startswith('_')]
>>> [n for n in dir(sys) if not n.startswith('_')]
['api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']
2)有用标准库
- time # 时间
- random # 返回随机数
- fileinput # 遍历文本文件所有行
- shelve # 存储数据
- re # 正则表达式
3)异常
Exception # 所有异常的基类
用try - except来捕捉异常:
try:
x = input('Enter a number:')
y = input('Enter anthor number:')
print x/y
except (ZeroDivisionError, TypeError, NameError) as e:
print "Your numbers were bogus..."
print e # 捕捉对象,记录异常
四、魔法方法、迭代和生成器等
1)魔法方法
Python当中,双下划线的方法是特殊的方法——魔法方法,比如__future__
,它们有特殊的含义,所以绝对不要在自己的程序中使用这种名字。
平时,init是比较重要的特殊方法,这个生成实例的时候做初始化。
2)迭代器
>>> it = iter([1,2,3])
>>> it.next()
1
>>> it.next()
2
>>> it.next()
3
>>> it.next()
Traceback (most recent call last):
File "<pyshell#226>", line 1, in <module>
it.next()
StopIteration