1.if __name__ == '__main__':

直接运行myModel.py时,当前模块的名字是main;import myModel然后运行的时候当前模块的名字是myModel。

2.eval: eval 函数的功能是将字符串生成语句并执行。

3.from module import class/func

module对应*.py文件,里面可以有class、func。class下还可以有func

4.利用set去重:links = [link for link in set(links)]

5.利用正则表达式匹配之后,根据组名取出值:

(?P<item_count>\d+)是一个分组,item_count是组名

ret = re.search(r'count:\'(?P<item_count>\d+)\'', html)
item_count = 0 if not ret else int(ret.group('item_count'))

6.python3,print作为函数使用:print("hello")

7.特殊变量_用于保存最后一次运算的结果

>>>600+100

700

>>>_+200

900

8.格式化输出:

print "%3d %0.2f" %(year,b)

print (format(year,"%3d"),format(b,"%0.2f"))

print "{0:3d} {1:0.2f}".format(year,b)    #冒号前面的数字表示传递给format()方法的参数

9:python没有switch、case语句,使用多个if elif else  语句代替

10.for语句:for i in xrange(0,10)

11.按行读文件:

for line in open("foo.txt"):

  print line

print写文件:

f = open("foo.txt",w)

while year<=nmyears:

  principal = principal * (1 + rate)

  print  >>f,"%3d %0.2f" % (year,principal)

  year +=1

f.close()

python3中不能使用>>,用下面代替:

print ("%3d %0.2f" % (year,principal),file = f)

write写文件:

f.write("%3d %0.2f\n" % (year,principal))

12.逻辑与、或、非:使用and、or、not

if a < 10 and a > :

  print a

if b < 10 or b > 20:

  print b

if  not c

  print c

13. utf8、gbk编码

>>> c=unicode('taobao_cocobella_35651013881_黑色','gbk').encode('utf8')
>>> c
'taobao_cocobella_35651013881_\xe9\xbb\x91\xe8\x89\xb2'

14.list、tuple、set、dict

list:可以增删,下标索引,连接。列表由于长度不固定,可增删,因此创建时会额外分配内存。

>>> a = [1,2,3,4,5]
>>> type(a)
<type 'list'>

>>> a[2]
3

>>> len(a)
5

>>> b = []
>>> c = list()

>>> b.append(a)
>>> b
[[1, 2, 3, 4, 5]]

tuple:不能增删,可以下标检索,连接,可以解包成变量,sql查询返回的就是tuple。元组由于长度固定,因此创建时分配内存就是这么大,不会额外分配。

>>> a =1,2,3,4
>>> a
(1, 2, 3, 4)
>>> type(a)
<type 'tuple'>

>>> b = ("hello",)
>>> b
('hello',)

>>> b[0]
'hello'

>>> studentInfo = ('Jack',24,'China')
>>> name,age,country = studentInfo
>>> name
'Jack'
>>> age
24
>>> country
'China'

>>> d = b + studentInfo
>>> d
('hello', 'Jack', 24, 'China')

可以list与tuple合起来用:

>>>students = []

>>> students.append(studentInfo)
>>> Hanmeimei = ('Hanmeimei',23,'USA')
>>> students.append(Hanmeimei)
>>> students
[('Jack', 24, 'China'), ('Jack', 24, 'China'), ('Hanmeimei', 23, 'USA')]

set:集合是无序的,可以用于去重,但是不能进行下标索引。支持并集、交集、差集、对称差集等。用add增加一项,update增加多项

>>> a = set()
>>> b = set([1,2,3,4,5])
>>> type(b)
<type 'set'>

>>> c = set([3,4,5,9,10,11])
>>> a = b | c
>>> d = b & c
>>> e = b - c
>>> f = b ^ c
>>> g = [a,d,e,f]
>>> g
[set([1, 2, 3, 4, 5, 9, 10, 11]), set([3, 4, 5]), set([1, 2]), set([1, 2, 9, 10, 11])]

>>> c.update([110,120,130])
>>> c
set([130, 3, 4, 5, 9, 10, 11, 110, 120])
>>> c.add(99)
>>> c
set([130, 3, 4, 5, 9, 10, 11, 110, 99, 120])

dict:字典,散列表。

>>> a = dict()
>>> b = {'name':'Jack','age':24,'country':'China'}
>>> b
{'country': 'China', 'age': 24, 'name': 'Jack'}

>>> b['name']
'Jack'

15.range、xrange

python3中xrange完全替换了python2中的range,统一成了range

在python2中,range(1000) 会立刻填满数据0,1,2。。。999

而xrange(1000)不会立刻填满,根据需要填值,省内存些。

16.生成器

使用yield的函数都是生成器,使用func.next()生成结果序列

>>> def func(n):
print 'Count down func. n = %s' % n
while n > 0:
yield n
n -=1

>>> count = func(10)
>>> count.next()
Count down func. n = 10
10
>>> count.next()
9
>>> for i in func(10):
print i

Count down func. n = 10
10
9
8
7
6
5
4
3
2
1

17.协程

使用(yield)创建协程,将输入参数作为一组任务,从而能处理一切发送过来的输入:

>>> def print_matches(matchText):
print "looking for",matchText
while True:
line = (yield)
if matchText in line:
print line

>>> matcher = print_matches('China')
>>> matcher.next()
looking for China
>>> matcher.send('fajsodfjaosidjfwodkfichafa asofjaofjwoijfoajsdf')
>>> matcher.send('I borned in China')
I borned in China

>>> matcher.close()

17.对象与类

dir()函数列出对象的所有可用方法,是交互试验的有用工具。

>>> dir(matcher)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']

>>> dir(dict())
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
>>> dir(set())
['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
>>> dir(list())
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> dir((1,2,3,4))
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

类的派生:

class Student(Person):

  

  def __init__(self,sname):#构造函数

    self.name = sname

def  getName()

    return self.name

@staticmethod

  def studentNum()

    pass

18.异常处理

(1)try except语句

try:

func()

excetp:

  print "error!"

(2)raise手动抛异常

func(n):

  if n < 0:

    raise valueError("n < 0")

这样调用func的地方就可以通过try捕获异常

(3)with语句

import threading

message_lock = threading .Lock()

...

with message_lock:

  message.add(newMessage)

with语句自动获取message_lock对象,当执行离开with代码块后(即message.add(newMessage)),后面的对象message_lock自动释放。无论with语句内部是否发生异常都将会释放该message_lock。有点类似于java中的finally语句。

19.模块

module.py文件作为一个模块,模块里面可以有class、普通方法(区别于类成员函数)

(1)import module                                  #导入模块

(2)from module import funcOrClass       #导入模块中的方法及类

(3)import module as otherModuleName  #使用别名导入模块

20.帮助信息

(1)help

>>> help(set)
Help on class set in module __builtin__:

class set(object)
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
|
| Methods defined here:
|
| __and__(...)
| x.__and__(y) <==> x&y
|
| __cmp__(...)
| x.__cmp__(y) <==> cmp(x,y)
|
| __contains__(...)
| x.__contains__(y) <==> y in x.
|
| __eq__(...)
| x.__eq__(y) <==> x==y

。。。

(2)__doc__

>>> print list.__doc__
list() -> new empty list
list(iterable) -> new list initialized from iterable's items

python参考手册--第1章python简介的更多相关文章

  1. python参考手册--第8章

    1.模块和import (1)首次import module会做以下3件事: a)创建新的命名空间,用作在该源文件中定义的所有对象的容器.在模块中定义的函数和方法在使用global语句时将访问该命名空 ...

  2. python参考手册--第9章

    1.读取命令行选项 (1)sys.args python启动时,命令行选项设置在列表sys.args中. sys.args[0]:xxx.py sys.args[1:]: 其他参数 (2)optpar ...

  3. python参考手册--第2章词汇和语法约定

    1.续行符\ 三引号.().{}.[]中的内容不需要续行符 2.空格缩进 优选空格作为缩进,不要用tab,这是因为不同操作系统下tab对应的空格不一样,而python是通过严格的空格来控制语句块的. ...

  4. python参考手册--第3章类型和对象

    1.对象的身份.类型.值 (1)身份:对象在内存中位置的指针,地址值, >>> a = [1,2,3,4,5] >>> id(a)48497328 >> ...

  5. 《python参考手册(第四版)》【PDF】下载

    <python参考手册(第四版)>[PDF]下载链接: https://u253469.pipipan.com/fs/253469-230382222 内容介绍 本书是权威的Python语 ...

  6. 《PYTHON学习手册》(《Learing Python》--Mark Lutz)书摘

    1. Python是为了让脚本的质量等级再提升几个级别. 2. <learning Python>和<programming Python>反映了作者培训内容的两部分:核心语言 ...

  7. [Python学习笔记][第七章Python文件操作]

    2016/1/30学习内容 第七章 Python文件操作 文本文件 文本文件存储的是常规字符串,通常每行以换行符'\n'结尾. 二进制文件 二进制文件把对象内容以字节串(bytes)进行存储,无法用笔 ...

  8. [Python学习笔记][第五章Python函数设计与使用]

    2016/1/29学习内容 第四章 Python函数设计与使用 之前的几页忘记保存了 很伤心 变量作用域 -一个变量已在函数外定义,如果在函数内需要修改这个变量的值,并将这个赋值结果反映到函数之外,可 ...

  9. [Python学习笔记][第四章Python字符串]

    2016/1/28学习内容 第四章 Python字符串与正则表达式之字符串 编码规则 UTF-8 以1个字节表示英语字符(兼容ASCII),以3个字节表示中文及其他语言,UTF-8对全世界所有国家需要 ...

随机推荐

  1. 8款强大的CSS3/HTML5动画及应用源码

    1.CSS3 jQuery UI控制滑杆插件 今天我们要来分享一款基于CSS3和jQuery UI的控制滑杆插件,这款控制滑杆是在HTML5滑杆元素的基础上进行自定义CSS3渲染,所以外观更加漂亮.另 ...

  2. POJ 1384

    求猜存钱罐中至少有多少钱.容易知道金币总的重量,接着背包. #include<cstdio> #include<iostream> using namespace std; # ...

  3. Essential C++ 学习笔记02--Array/Vector 与指针

    Essential C++ 1.5-1.6节,3.1节笔记 Array/Vector/指针,难度偏大, 但若学习初期不熟悉基本用法,则难以写出有效代码. 1. 基本概念 Array 是一段连续内存,数 ...

  4. 这是html5中WebGL的演示

    这是html5中WebGL的演示,让我们与他人分享爱您发送短消息.每次你进入它使用不同的位置,新的爱情点被添加到全球.让世界更明亮的地方与你的朋友分享! 源文件:部分代码:<!DOCTYPE h ...

  5. git 合并本地代码到分支

    本地代码合并到dev分支 在local分支提交git add .git commit -m "playbuy" 切换到dev分支git checkout devgit pull合并 ...

  6. i18next-页面层语言国际化js框架介绍

    因为工作需要,最近研究了下网站语言国际化的问题,根据当前项目架构,寻求一种较好的解决方案.首先总结下项目中语言切换实现方式大概有以下几种: 1,一种语言一套页面,如:index_CN.html,ind ...

  7. HTML5特性:使用async属性异步加载执行JavaScript

    HTML5让我兴奋的一个最大的原因是,它里面实现的新功能和新特征都是我们长久以来一直期待的.比如,我以前一直在使用placeholders,但以前必须要用JavaScript实现.而HTML5里给Ja ...

  8. Ant之build.xml

    转载地址:http://www.cnblogs.com/clarkchen/archive/2011/03/10/1980194.html http://lisongqiu168.iteye.com/ ...

  9. 2.opencv图像处理常用操作

    图像的平滑处理 平滑,也称 模糊, 平滑处理时需要用到一个滤波器 .滤波器想象成一个包含加权系数的窗口,这个加权系数也叫做核或者模版. // 图像平滑处理分而学之.cpp : 定义控制台应用程序的入口 ...

  10. 表达式语言之java对正则表达式的处理

    正则表达式用于字符串匹配,字符串查找,字符串替换等.例如注册email格式的验证等.java中处理正则表达式相关的类主要有java.lang.String,java.util.regex.Patter ...