# 《简明Python教程》学习笔记

2013-07-11

help(sys)
help(int)
help(list)
help(dict)
help(str)
help(file)
sys模块
print sys.__doc__
help(sys.exit)
help(sys.stdin)
help(sys.stdout)
help(sys.stderr)
1.

2.
-25.5%2.25=1.5
3.
**是幂运算，布尔（not、or、and）逻辑（&，|，^，~）
4.

area = 5
print &#39;Area is&#39;, area
Area is 5[自动输出1个空格]
5.
if condintion1:
func1
elif condition2:
func2
else :
func3

6.
guess = int(raw_input(&#39;Enter an integer:&#39;))

7.
True、False、None首字母不能小写。
8.
#while
while condtion1:
func1
else:
func2
#for
for i in range(1,5):
func1
else:
func2

else从句可有可无

9.
range(begin,end,step)
range 以step为步长，延伸到end，但它不包含end。
10.
【Python的for循环更加简单、明白、不易出错。】

11.
def sayHello():
print &#39;Hello world!&#39;
sayHello()
12.
global x,y,z
13.
print &#39;zhanghe&#39;*5
14.

func(50,c=100)

15.

16.
pass语句在Python中表示一个空的语句块。
17.

18.

19.

>>> import sys
>>> dir(sys) # get list of attributes for sys module
>>> dir() # get list of attributes for current module
>>> a = 5 # create a new variable &#39;a&#39;
>>> dir()
>>> del a # delete/remove a name
>>> dir()
20.

#Filename:using_list.py
shoplist = [&#39;apple&#39;,&#39;mango&#39;,&#39;carrot&#39;,&#39;banana&#39;]
print &#39;I hava&#39;,len(shoplist),&#39;items to purchase.&#39;
print &#39;These items are:&#39;,#Notice that comma at end of the line
for item in shoplist:
print item,
#These items are: apple mango carrot banana
print &#39;\nI also have to buy rice.&#39;
shoplist.append(&#39;rice&#39;)
print &#39;My shopping list is now&#39;,shoplist
#My shopping list is now [&#39;apple&#39;, &#39;mango&#39;, &#39;carrot&#39;, &#39;banana&#39;, &#39;rice&#39;]
print &#39;I will sort my list now&#39;
shoplist.sort()
print &#39;Sorted shopping list is&#39;,shoplist
print &#39;The first item I will buy is&#39;,shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print &#39;I bought the&#39;,olditem
print &#39;My shopping list is now&#39;,shoplist
21.

22.

#Filename:using_tuple.py
zoo = (&#39;wolf&#39;,&#39;elephant&#39;,&#39;penguin&#39;)
print &#39;Number of animals in the zoo is&#39;,len(zoo)
new_zoo = (&#39;monkey&#39;,&#39;dolphin&#39;,zoo)
print &#39;Number of animals in the new zoo is&#39;,len(new_zoo)
print &#39;All animals in new zoo are&#39;,new_zoo
print &#39;Animals brought from old zoo are&#39;,new_zoo[2]
print &#39;Last animal brought from old zoo is&#39;,new_zoo[2][2]
output:
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are (&#39;monkey&#39;, &#39;dolphin&#39;, (&#39;wolf&#39;, &#39;elephant&#39;, &#39;penguin&#39;))
Animals brought from old zoo are (&#39;wolf&#39;, &#39;elephant&#39;, &#39;penguin&#39;)
Last animal brought from old zoo is penguin

23.

age = 22
name = &#39;Swaroop&#39;
print &#39;%s is %d years old&#39; % (name, age)
print &#39;Why is %s playing with that python?&#39; % name
24.

#Filename:using_dict.py
#&#39;ab&#39; is short for &#39;a&#39;ddress &#39;b&#39;ook
ab={ &#39;Swaroop&#39; : &#39;swaroopch@byteofpython.info&#39;,
&#39;Larry&#39; : &#39;larry@eall.org&#39;,
&#39;Matsumoto&#39; : &#39;matz@ruby-lang.org&#39;,
&#39;Spammer&#39; : &#39;spammer@hotmail.com&#39; #The last para has no &#39;,&#39;
}
print "Swaroop&#39;s address is %s" % ab[&#39;Swaroop&#39;]
ab[&#39;Guido&#39;] = &#39;guido@python.org&#39;
#Deleting a key/value pair
del ab[&#39;Spammer&#39;]
print &#39;\nThere are %d contacts in the address-book\n&#39;%len(ab)
if &#39;Guido&#39; in ab:#OR ab.has_key(&#39;Guido&#39;)
25.

# Filename: seq.py
shoplist = [&#39;apple&#39;, &#39;mango&#39;, &#39;carrot&#39;, &#39;banana&#39;]
# Indexing or &#39;Subscription&#39; operation
print &#39;Item 0 is&#39;, shoplist[0]
print &#39;Item 1 is&#39;, shoplist[1]
print &#39;Item 2 is&#39;, shoplist[2]
print &#39;Item 3 is&#39;, shoplist[3]
print &#39;Item -1 is&#39;, shoplist[-1]
print &#39;Item -2 is&#39;, shoplist[-2]
# Slicing on a list
print &#39;Item 1 to 3 is&#39;, shoplist[1:3]
print &#39;Item 2 to end is&#39;, shoplist[2:]
print &#39;Item 1 to -1 is&#39;, shoplist[1:-1]【notice that】
print &#39;Item start to end is&#39;, shoplist[:]【notice that】
# Slicing on a string
name = &#39;swaroop&#39;
print &#39;characters 1 to 3 is&#39;, name[1:3]
print &#39;characters 2 to end is&#39;, name[2:]
print &#39;characters 1 to -1 is&#39;, name[1:-1]
print &#39;characters start to end is&#39;, name[:]
output：
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Item 1 to 3 is [&#39;mango&#39;, &#39;carrot&#39;]
Item 2 to end is [&#39;carrot&#39;, &#39;banana&#39;]
Item 1 to -1 is [&#39;mango&#39;, &#39;carrot&#39;]【notice that】
Item start to end is [&#39;apple&#39;, &#39;mango&#39;, &#39;carrot&#39;, &#39;banana&#39;]【notice that】
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
26.

#Filename:reference.py
print &#39;Simple Assignment&#39;
shoplist = [&#39;apple&#39;,&#39;mango&#39;,&#39;carrot&#39;,&#39;banana&#39;]
mylist = shoplist #mylist is just another name pointing to the same object
del shoplist[0]
print &#39;shoplist is&#39;,shoplist
print &#39;mylist is&#39;,mylist
# notice that both shoplist and mylist both print the same list without
# the &#39;apple&#39; confirming that they point to the same object
print &#39;Copy by making a full slice&#39;
mylist = shoplist[:]# make a copy by doing a full slice
del mylist[0]
print &#39;shoplist is&#39;,shoplist
print &#39;mylist is&#39;,mylist
# notice that now the two lists are different
27.

#!/usr/bin/python
#Filename:str_methods.py
name = &#39;Swaroop&#39; #This is a string object
if name.startswith(&#39;Swa&#39;):
print &#39;This string starts with "Swa"&#39;
if &#39;a&#39; in name:
print &#39;This string contains the string "a"&#39;
if name.find(&#39;war&#39;) != -1:
print &#39;This string contains the string "war"&#39;
delimiter = &#39;_*_&#39;
mylist = [&#39;Brazil&#39;, &#39;Russia&#39;, &#39;India&#39;, &#39;China&#39;]
print delimiter.join(mylist)
28.

29
__init__
__init__方法在类的一个对象被建立时，马上运行。这个方法可以用来对你的对象做一些你希望的 初始化 。注意，这个名称的开始和结尾都是双下划线。
30.

#Filename:objvar.py
class Person:
&#39;&#39;&#39;Represents a person.&#39;&#39;&#39;
population = 0
def __init__(self, name):
&#39;&#39;&#39;Initializes the person&#39;s data.&#39;&#39;&#39;
self.name = name
print &#39;(Initializing %s)&#39;%self.name
#When this person is created, he/she
Person.population += 1
def __del__(self):
&#39;&#39;&#39;I am dying&#39;&#39;&#39;
print &#39;%s says bye.&#39;%self.name
Person.population -= 1
if Person.population == 0:
print &#39;I am the last one&#39;
else :
print &#39;There are still %d people left.&#39;%Person.population
def sayHi(self):
&#39;&#39;&#39;Greeting by the person.
Really,that&#39;s all it does.&#39;&#39;&#39;
print &#39;hi,my name is %s.&#39;%self.name
def howMany(self):
&#39;&#39;&#39;Prints the current population.&#39;&#39;&#39;
if Person.population == 1:
print &#39;I am the only person here.&#39;
else:
print &#39;We have %d persons here.&#39;%Person.population
swaroop = Person(&#39;Swaroop&#39;)
swaroop.sayHi()
swaroop.howMany()
kalam = Person(&#39;Abdul Kalam&#39;)
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
kalam.__del__()
swaroop.__del__()
31.
Python要求：
Python中所有的类成员（包括数据成员）都是 公共的 ，所有的方法都是 有效的 。

32.

33.
Python不会自动调用基本类的constructor，你得亲自专门调用它。

34.
Python提供一个标准的模块，称为pickle。使用它你可以在一个文件中储存任何Python对象，之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。

dump()储存
35.

36.

37.
try..finally

import time
time.sleep(2)
38.

39.
sys模块
40.
os模块

>>> import os
>>> str = &#39;Path&#39;
>>> print os.getenv(str)
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;E:\Java\jdk1.6.0_21\bin;C:\Python27;

os.name字符串指示你正在使用的平台。比如对于Windows，它是&#39;nt&#39;，而对于Linux/Unix用户，它是&#39;posix&#39;。
os.getcwd()函数得到当前工作目录，即当前Python脚本工作的目录路径。
os.getenv()和os.putenv()函数分别用来读取和设置环境变量。
os.listdir()返回指定目录下的所有文件和目录名。
os.remove()函数用来删除一个文件。
os.system()函数用来运行shell命令。
os.linesep字符串给出当前平台使用的行终止符。例如，Windows使用&#39;\r\n&#39;，Linux使用&#39;\n&#39;而Mac使用&#39;\r&#39;。
os.path.split()函数返回一个路径的目录名和文件名。
os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地，os.path.existe()函数用来检验给出的路径是否真地存在。
41.

__init__(self,...) 这个方法在新建对象恰好要被返回使用之前被调用。
__del__(self) 恰好在对象要被删除之前调用。
__str__(self) 在我们对对象使用print语句或是使用str()的时候调用。
__lt__(self,other) 当使用 小于 运算符（<）的时候调用。类似地，对于所有的运算符（+，>等等）都有特殊的方法。
__getitem__(self,key) 使用x[key]索引操作符的时候调用。
__len__(self) 对序列对象使用内建的len()函数的时候调用。
42.

if True: print &#39;Yes&#39;
43.

44.

45.
lambda形式
lambda语句被用来创建新的函数对象，并且在运行时返回它们。
lambda需要一个参数，后面仅跟【单个表达式】作为函数体，而表达式的值被这个新建的函数返回。
46.
exec语句
exec语句用来执行储存在字符串或文件中的Python语句。
exec &#39;print "Hello World"&#39;
eval语句
eval语句用来计算存储在字符串中的有效Python表达式。
eval(&#39;2*3&#39;)
assert语句
assert语句用来声明某个条件是真的。例如，如果你非常确信某个你使用的列表中至少有一个元素，而你想要检验这一点，并且在它非真的时候引发一个错误，那么assert语句是应用在这种情形下的理想语句。
repr函数
repr函数用来取得对象的规范字符串表示。反引号（也称转换符）可以完成相同的功能。
repr函数和反引号用来获取对象的可打印的表示形式。你可以通过定义类的__repr__方法来控制你的对象在被repr函数调用的时候返回的内容。
>>> i = []
>>> i.append(&#39;item&#39;)
>>> `i`
"[&#39;item&#39;]"
>>> repr(i)
"[&#39;item&#39;]"
【QQ:1203456195】【博客地址：http://www.cnblogs.com/CheeseZH】