显示标签为“Python”的博文。显示所有博文
显示标签为“Python”的博文。显示所有博文

2010/03/14

Python 简明学习笔记(三)

九:面向对象编程
类使用class关键字创建,类的域和方法被列在一个缩进中。

定义在类中的方法必须有一个额外的第一参数名称,按照惯例它的名称为self,它指的是对象本身。python中的self相当于Java中的this。

eg:
#!/usr/bin/python
#Filename:simplecalss.py

class Person:
    def sayHello(self):
        print'hello ,how are you ?'

p=Person()
p.sayHello()
#也可写作Person().sayHello()

__init__方法:相当于Java中的构造器,在类的第一个对象被建立时,立即运行。用于对对象做一些初始化。

#!/usr/bin/python
#Filename:class_init.py

class Person:
    def __init__(self,name):
        self.name=name
    def sayHello(self):
        print'hello, my name is ',self.name

p=Person('anix')
p.sayHello()

output:
$python class_init.py
hello, my name is anix
#有两种类型的域——类的变量和对象的变量。他们是根据是类还是对象拥有这个变量而区分的。self.name=name:Person('anix')是将anix传递给类,此时name是类变量,self.name=name将类变量赋值给对象变量。(self指的是对象本身)。

类的变量由一个类的所有对象(实例)共享使用,所以当某个对象对类的变量作出的改动会影响所有该类的实例。

对象的变量由每个对象/实例拥有。每个对象有自己对这个域的一份拷贝,所有当某个对象对对象的变量作出的改动不会影响其他该类的实例。

eg:

#!/usr/bin/python
#Filename:objvar.py

class Person:
    '''represents a person'''
    population=0

    def __init__(self,name):
        '''initializes the person's data'''
        self.name=name
        print'(initializing %s)'% self.name
        Person.population++

    def __del__(self):
        print'%s says goodbye.'% self.name   
        Person.population--
        if Person.population==0:
            print'i am the last one'
        else:
            print'there is %d people left.' % \
                    Person.population
   
    def sayHello(self):
        print'hello, my name is %s' % self.name

    def howMany(self):
        if Person.population==1:
            print'i am the only person here'
        else:
            print'there are %d persons here' %\
                     Person.population

anix=Person('anix')
anix.sayHello()
anix.howMany()

chris=Person('Chris')
chris.sayHello()
chris.howMany()

anix.__del__()
anix.howMany()

#population属于Person类,是类变量。
#name是对象变量,它使用self赋值。
#__del__方法在对象不再被时候时运行(相当于Java中的system.gc()),当需要指明它何时运行时就得使用与此例相似的del语句。

output:
(initializing anix)
hello, my name is anix
i am the only person here'
(initializing Chris)
hello, my name is Chris
there are 2 person here
anix says goodbye
i am the only person here'

继承:

eg:

#!/usr/bin/python
# Filename: inherit.py

class SchoolMember:
    '''Represents any school member.'''
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print '(Initialized SchoolMember: %s)' % self.name
    def tell(self):
    '''Tell my details.'''
        print 'Name:"%s" Age:"%s"' % (self.name, self.age)

class Teacher(SchoolMember):
    '''Represents a teacher.'''
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)
        self.salary = salary
        print '(Initialized Teacher: %s)' % self.name
    def tell(self):
        SchoolMember.tell(self)
        print 'Salary: "%d"' % self.salary

class Student(SchoolMember):
    '''Represents a student.'''
    def __init__(self, name, age, marks):
        SchoolMember.__init__(self, name, age)
        self.marks = marks
        print '(Initialized Student: %s)' % self.name
    def tell(self):
        SchoolMember.tell(self)
        print 'Marks: "%d"' % self.marks

t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)
print # prints a blank line
members = [t, s]
for member in members:
    member.tell() # works for both Teachers and Students

输出
$ python inherit.py
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)
Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
Name:"Swaroop" Age:"22" Marks: "75"



十:I/O

文件:通过创建file类对象打开一个文件,使用file类的read write readline方法来恰当地读写文件,然后调用close方法关闭文件。

#!/usr/bin/python
#Filename:using_file.py

poem='''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f=file('poem.txt','w')
f.wirte(peom)
f.close()

f=file('poem.txt') #默认为'r'ead模式
while True:
    line=f.readline()
    if len(line)==0:
        break
    print line
f.close()

#文件的模式:读模式('r');写模式('w');追加模式('a')

output:
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!


储存器:python提供名为pickle的标准模块,使用它可以在一个文件中储存任何python对象,并完整取出来。这被称为持久地储存对象。
另外还有一个模块叫 cPickle,用C语言实现,功能和pickle模块完全相同,但速度比pickle模块快1000倍。

dump(obj,file) load(file)
eg:

#!/usr/bin/python
#Filename:pickling.py

import cPickle as p

shoplistfile='shoplist.txt'
shotlist=['apple','orange','egg','banana','fish','beef','celery']

#write to the file
f=file(shoplistfile,'w')
p.dump(shoplist,f) #dump the object to the file
f.close()

#pick up from the storage
f=file(shoplistfile)
storedlist=p.load(f)

print storedlist

output:
['apple','orange','egg','banana','fish','beef','celery']


十一:异常 exceptions

try...except语句处理异常。


eg:
#!/usr/bin/python
#Filename try_except.py

import sys

try
    s=raw_input('enter something')
except EOFError:
    print'\n EOF error'
except:
    print'\n some error/exception occurred.'
print 'Done.'


raise 引起异常:
#!/usr/bin/python
#Filename :raising.py

import sys

calss ShortInputException(Exception):
    '''a user-defined exception'''
    def __init__(self,length,atleast):
        Exception.__init__(self)
        self.length=length
        self.atleast=atleast

try:
    s=raw_input('enter something:')
    if len(s)<3:
        raise ShortInputException(len(s),3)
except EOFError:
    print'\n EOF error.'
except ShortInputException,x:
    print'shortinput exception: the input was of length %d,\
        was excepting at least %d'%(x.length,x.atleast)
else:
    print'NO exception was raised.'



try...finally语句:
#!/usr/bin/python
#Filename: finally.py

import time

try:
    f=file('poem.txt')
    while True:
        line=f.readline()
        if len(line)==0:
            break
        time.sleep(2)
        print line
finally:
    f.close()
    print'close file'



十二:python标准库

在python附带的安装文档的“库参考”一节中有python所有模块的完整内容。

sys模块:包含系统对应的功能。

eg:使用sys.argv,实现unix下 cat功能:

#!/usr/bin/python
#Filename:cat.py

import sys

def readfile(filename):
    f=file(filename)
    while True:
        line=f.readline()
        if len(line)==0:
            break
        print line
    f.close()

if len(sys.argv)<2:
    print'no action specified'
    sys.exit()

if sys.argv[1].startswith('--'):
    option=sys.argv[1][2:]
    if option=='version':
        print'version 1.2'
    elif option=='help':
        print '''\
    this program prints files to standard output
    '''
    else:
        print 'unknown option.'
    sys.exit()
else:
    for filename in sys.argv[1]:
        readfile(filename)



os模块:包含普遍的操作系统功能,对解决跨平台问题十分重要。如使用os.sep可以取代操作系统特定的路径分隔符。

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


十三:更多内容

·特殊的方法:
一般来说,特殊的方法都被用来模仿某个行为。例如,如果想使用x[key]这样的索引操作(如列表和元组),那么只需要实现__getitem__()方法就可以了。

一些常见的特殊方法:

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



·单语句块:
大多数情况下,python每个语句块是通过它的缩进层次与其他块区分开的。但如果语句块只包含一句指令,可以在条件语句或循环语句的同一行指明它,如:
>>>flag=True
>>>if flag : print 'yes'

>>>for filename in sys.argv[1]: readfile(filename)


·列表综合:
通过列表综合,可以从一个已有列表中导出新的列表。例如:已知一个数列,希望得到一个对应的数列,原数列中所有大于2的数都是原来的2倍:

#!/usr/bin/python
#Filename:list_comprehension.py

listone=[2,3,4]
listtwo=[2*i for i in listone if i>2]
print listtwo

output:
[6,8]


·在函数中接收元祖和列表:
当要使函数接收元祖或字典形式的参数时,有一种特殊方法,它分别使用*和**前缀,这种方法在函数需要获取数量可变的参数时候十分有用。
>>>def powersum(power,*args):
    total=0
    for i in args:
        total+=pow(i,power) #即i^power
    return total

output:
>>>powersum(2,3,5)
25
>>>powersum(2,10)
100


·lambda形式
lambda语句被用来创建新的函数对象,并在运行时返回他们。
eg:使用lambda形式

#!/usr/bin/python
#Filename:lambda.py

def make_repeater(n):
    return lambda s:s*n

twice=make_repeater(2)

print twice('word')
print twice(5)

#make_repeater函数在运行时创建新的函数对象,并返回它。lambda语句用来创建函数对象。
#本质上,lambda需要一个参数(这里是s),后面仅跟单个表达式作为函数体(这里是s*n),函数体(表达式)的值作为被lambda新建的函数返回(这里返回s*n的值)。


·exec和eval语句:
exec语句用来执行存储在*字符串*或*文件*中的python语句,例如我们可以在运行时生成一个包含python代码的字符串,然后使用exec语句执行之:
>>>exec 'print"hello world"'
hello world

eval语句用于计算存储在字符串中的有效python表达式:
>>>eval('2**3')
8
#'2**3'是一个字符串,因为被''罩住。


·assert语句:
assert语句用来声明某个条件是真的。例如,如果你非常确信某个你使用的列表中至少有一个元素,而你想要检验这一点,并且在它非真的时候引发一个错误,那么assert语句是应用在这种情形下的理想语句。当assert语句失败的时候,会引发一个AssertionError。

>>>mylist=['list']
>>>assert len(mylist)>=1
>>>mylist.pop()        #弹出mylist列表中元素并输出
list
>>>assert len(mylist)>=1
Traceback (most recent call last):
File "", line 1, in ?
AssertionError


·repr函数:
repr函数用来取得对象的规范字符串表示。反引号(也称转换符)可以完成相同的功能。注意,在大多数时候有eval(repr(object)) == object。

>>> i = []
>>> i.append('item')        #向列表中增加条目
>>> `i`
"['item']"
>>> repr(i)
"['item']"

基本上,repr函数和反引号用来获取对象的可打印的表示形式。你可以通过定义类的__repr__方法来控制你的对象在被repr函数调用的时候返回的内容。



十四:
www.google.com ,它会告诉你想要知道的一切. ^_^






注:此教程是我在2010寒假中学习Python的学习笔记。

Python 简明学习笔记(二)

六:函数

函数是重用的字符串.
函数的定义通过关键词 def

def <函数名>():
<函数体>

函数的形参:参数在函数定义的圆括号内指定,用逗号分隔。
函数的实参:调用函数时,按照形参的格式交由函数处理的数据叫做实参。

eg:
#!/usr/bin/python
#Filename: func_param.py

def printMax(a,b):
    if a>b:
        print a
    else:
        print b

printMax(3,4)

局部变量:没有特殊声明,在函数内定义的变量都是局部变量,其作用域始于定义处,终止于函数结尾。

使用global语句:将变量生命为全局变量。
eg:

#!/usr/bin/python
#Filename:func_global.py
a=10
def func():
    global x
    print 'x=',x
    x=2
    print'changed local x to ',x
    a=20
    print 'a in the func is',a

x=50
print 'a in the outer is ',a
func()
print 'value of a is',a
pirnt 'value of x is ',x

output:
a in the outer is 10
x=50
changed local x to 2
value of a is 10
value of x is 2

默认参数值:对于一些函数,希望它的一些参数是可选的,如果用户互相为这类参数提供值的话,这些参数使用默认值。

eg:
#!/usr/bin/python
#Filename:func_default.py

def say(message,times=1):
    print message*times

say ('hello')
say ('world',5)

output:
hello
worldworldworldworldworld

关键参数:一个函数有多个参数,作者只想指定其中一部分,那么作者可以通过命名来为这些参数赋值,这些参数被称为关键参数,用户用名字(关键字)而不是闻之来给参数指定实参。
eg:

#!/usr/bin/python
#Filename:func_key.py

def func(a,b=5,c=10)
    print'a =',a,'b=',b,'c=',c

func(1)
func(2,c=30)
func(c=40,a=3)

output:
a=1,b=5,c=10
a=2,b=5,c=30
a=3,b=5,c=40

return语句:return语句用来从一个函数返回,即跳出函数。
eg:
#!/usr/bin/python
#Filename:func_return.py

def maxnum(x,y):
    if x>y:
        return x
    else:
        return y

print maxnum(2,3)


DocStrings,文档字符串:有点像javadoc

#!/usr/bin/python
# Filename: func_doc.py

def printMax(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
    x = int(x) # convert to integers, if possible
    y = int(y)
    if x > y:
        print x, 'is maximum'
    else:
        print y, 'is maximum'

printMax(3, 5)
print printMax.__doc__  #双下划线,Python中的
            #help()命令其实就是抓取程序的__doc__属性

output:
$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.
The two values must be integers.



七:模块
模块基本上是一个包含了所有你定义的函数和变量的文件。模块文件必须以.py为扩展名。
模块可以从其他程序调入,以便利用它的功能。这也是我们使用Python标准库的方法。

#!/usr/bin/python
#Filename:using_sys.py

import sys

print 'the command line arguments are:'
for i in sys.argv:
    print i

print'\n\n the pythonpath is :\n',sys.path,'\n'


output:
$python using_sys.py we are arguments
the command line arguments are:
using_sys.py
we
are
arguments
the pythonpath is :
['/home/swaroop/byte/code', '/usr/lib/python23.zip',
'/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2',
'/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload',
'/usr/lib/python2.3/site-packages', '/usr/lib/python2.3/site-packages/gtk-2.0']

#字节编译的.pyc文件:程序处理一个模块比较耗费资源,如果将模块编译成字节码的.pyc为扩展名的文件,效率将大大提高。这些字节码也是与平台无关的。

#from...import语句:
如果你想要直接输入argv变量到你的程序中(避免在每次使用它时打sys.),那么你可以使用from sys import argv语句。如果你想要输入所有sys模块使用的名字,那么你可以使用from sys import *语句。这对于所有模块都适用。一般说来,应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突。

模块的__name__属性:模块的名字
使用__name__属性的一种情况:当模块第一次被import时,这个模块的主模块就会被运行,假如我们只希望在程序被使用的时候运行模块,而不是在它被别动载入的时候,可以通过此属性完成。

#!/usr/bin/python
#Filename:using_name.py

if __name__=='__main__':
    print 'this program is being running by itself '
else:
    print:'i am bing imported from another module'

输出:
$python using_name.py
this program is being running by itself
$python
>>>imort using_name.py
i am bing imported from another module
>>>


创建用户模块:每个python程序都是一个模块
eg:
#!/usr/bin/python
#Filename:mymodule.py

def sayhello():
    print'hello ,this is mymodule speaking.'
version='0.1'
#end of mymodule.py
#注意:此模块需要被放置在import它程序的同一目录,或放在sys.path中。

#!/usr/bin/python
#Filename:using_mymodule.py

import mymodule
mymodule.sayhello()
print 'version:' ,mymodule.version

output:
hello ,this is mymodule speaking
version:0.1



dir()函数:内建函数,列出模块定于的标识符(包含函数.类.变量等)
eg:
$python
>>>import sys
>>> dir (sys) #get list of attributes of sys module
.....
>>>dir() #get list of attributes of current module
.....
>>>a=5 #create a new variable 'a'
>>>dir()
.....
['__builtins__', '__doc__', '__name__', 'a', 'sys']
>>>del a #delete/remove a name
>>>dir()
.....
>>>


八:解决问题:python脚本

备份脚本 version 1:

#!/usr/bin/python
#Filename:backup_ver1.py

import os
import time

#the files and dirs that you wanna to backup
#if you are using windows,use source=[r'c:\documents',r'd:\dev']
source=['/home/anix/document','/etc/','/usr/bin/']

#the directory that the backup files are stored
target_dir='/media/backup/'

#the name of the backup archieve
target=target_dir+os.sep+time.strftime(%Y%m%d%H%M%S')+'.tar.gz'

#the command string
tar_command="tar -cvzf %s %s"%(target,''.join(source))

#run the script
if os.system(tar_command)==0:
    print'successful backup to',target
else:
    print'backup failed'




#!/usr/bin/python
#Filename:backup_ver2.py

import os
import time

source=['/home/anix','/etc/']
target_dir='/media/backup'
today=target_dir+time.strftime('%Y%m%d')
now=time.strftime('%H%M%S')

if not os.path.exists(today):
    os.mkdir(today)
    print'successfully created directory',today
target=today+os.sep+now+'.tar.gz'

tar_command='tar cvzf %s %s' %(target,''.join(source))

if os.system(tar_command)==0:
    print'successful backup to ',target
else:
    print'backup failed'


软件开发过程:分析->设计->编写->测试->使用->维护(优化)

Python 简明学习笔记(一)

               Python 简明学习笔记

一:最初的步骤:
    ・添加环境变量:path=%path%;c:\python26;.
    ・第一个helloworld程序:
    #!/usr/bin/python
    #Filename:hellowrold.py
    pirnt 'hello world'
   
    运行:Python helloworld.py
    输出:hello world


二:基本概念:

常量:不能改变值的量
数:
    整数:int
    长整数:long //int和long 有合并的趋势,长整形所表达的数的最大值取决于用户计算机的虚拟内存总数,与java中的bigInterger相似。
    浮点数:float 如:2.23E-4
    复数: -5+3j
    decimal:用于十进制浮点数。并非内建,使用前需导入decimal模块。例如:由于二进制表示中有一个无限循环片段,数字1.1无法用二进制浮点数精确表示,如:
        >>>1.1
        1.1000000000000000000001
        >>>print decimal.Decimal('1.1')
        1.1


字符串:string
    ・使用单引号('')
      引号中的所有空白都原样保留,如'this is a python example'
    ・使用双引号("")
      同单引号。
    ・使用三引号('''或""")
      用于指示一个多行字符串,在其中可以自由使用'和":
    '''example of multi-line string.
    "what is your name ?"
    'my name is anix.'
    '''
    ・转义符:(\)
      如:'what\'s your name?' //注意这里也可以用双引号而不使用转义符:"what's your name?"
      又如:"this is the first sentence.\
        this is the second one."等价于"this is the first sentence.this is the second one."
    ・自然字符串:如果需要指定某些不需要如转义符那样的特别处理字符串,那么需要指定为自然字符串,自然字符串通过给字符串加上前缀r或R指定:如:
        r 'newlines are indicated by \n'
    ・Unicode字符串
    字符串中包含非拉丁字母时,需要被指定为Unicode字符串,制定方法为在字符串前加上前缀U或u,如:U"这是简体中文。"
    ・星号*
      表示重复,如:
        >>>pystr='hello'
        >>>pystr * 2
        hellohello
        >>>'-'*10
        '----------'
tips:字符串是不可变的。

变量
标示符的命名:
    ・标示符的第一个字符必须是字母表中的字母或一个下划线'_'
    ・标示符其他部分可以由字母,下划线,数字组成。
    ・标示符对大小写敏感。

数据类型:变量可以处理的不同类型的值称为数据类型
对象

三:运算符与表达式

运算符        说明        例子
+                3+5得8.'a'+'b'得'ab'
-
*                2*3得6;'ha'*3得'hahaha'
**        返回x的y次幂    2**10得 1024
/                4/3得1;4.0/3得1.333333
//        取整        4/3.0得1.0
%        取模        4//3.0得1;8%3得2;-25.5%2.25得0.75

<<        左移        2<<1得4
>>        右移        2>>1得1;3>>1得1
&        按位与
|        按位或       
^        按位非
~        按位翻转(x的按位翻转式-(x+1)) ~5得-6
<
>
<=
>=
==
!=
not        布尔非
and        布尔与
or        布尔或

运算符优先级:

运算符         描述
lambda         Lambda表达式
or         布尔“或”
and         布尔“与”
not x         布尔“非”
in,not in     成员测试
is,is not     同一性测试
<,<=,>,>=,!=,==    比较
|         按位或
^         按位异或
&         按位与
<<,>>         移位
+,-         加法与减法
*,/,%        乘法、除法与取余
+x,-x         正负号
~x         按位翻转
**         指数
x.attribute     属性参考
x[index]     下标
x[index:index]     寻址段
f(arguments...)     函数调用
(experession,...)     绑定或元组显示
[expression,...]     列表显示
{key:datum,...}     字典显示
'expression,...'     字符串转换

四:数据结构

1:list tuple
列表和元组可以被看做是数组,可以存储任意类型数据,并可以用切片操作[],[:]得到子集。
区别是:1:列表用[]包裹,元组用()包裹;2:列表元素可以修改,而元组数据不可以修改。
>>>alist=[1,2,3,4]
>>>alist
[1,2,3,4]
>>>alist[0]
1
>>>alist[2:] #从第三个元素开始到结尾(包括第三个)
[3,4]
>>>alist[:3] #从头到第四个元素(不包括第四个)
[1,2,3]
>>>alist[0]=5
>>>alist
[5,2,3,4]

>>>atuple=('apple',3,7,'orange')
>>>atuple
('apple',3,7,'orange')
>>>atuple[:3]
('apple',3,7)
>>>atuple[2:]
(7,'orange')
>>>atuple[1:3]
(3,7)


2:字典 map
工作原理类似哈希表,是由key-value对组成,用{}包裹,key和value之间用':'分割,不同key-value对之间用','分割。

>>>adict={'host':'google.com','dns':'8.8.8.8'}
>>>adict['port']=23
>>>adict
{'host':'google.com','dns':'8.8.8.8','port':23}
>>>adict['host']
'google.com'
>>>adict.keys()
['host','dns','port']
>>>for key in adict:
   print key,adict[key]
```
host google.com
dns 8.8.8.8
port 23

3:序列

元组、列表和字符串都属于序列。序列的两个主要特点是:索引操作符和切片操作符。索引操作符可从序列中抓取一个特定项目,切片操作符可以从序列中获取一个子集。
Python中序列的一个重要特点是索引可以为负值:-1表示最后一个元素,,-2表示倒数第二个元素......
eg:

#!/usr/bin/python
# Filename: seq.py
shoplist = ['apple', 'mango', 'carrot', 'banana']
# Indexing or 'Subscription' operation
print 'Item 0 is', shoplist[0]
print 'Item 1 is', shoplist[1]
print 'Item 2 is', shoplist[2]
print 'Item 3 is', shoplist[3]
print 'Item -1 is', shoplist[-1]
print 'Item -2 is', shoplist[-2]
# Slicing on a list
print 'Item 1 to 3 is', shoplist[1:3]
print 'Item 2 to end is', shoplist[2:]
print 'Item 1 to -1 is', shoplist[1:-1]
print 'Item start to end is', shoplist[:]
# Slicing on a string
name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]

输出
$ python seq.py
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 ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop


4:引用
当在计算机中创建一个对象并把它赋予一个变量时,这个变量仅仅引用那个对象,而不是表示这个对象本身,两者只是存在绑定关系。还可以有其他变量指向同一个对象。

eg:

#!/usr/bin/python
#!Filename:reference.py

shoplist=['apple','mango','carrot','banana']
mylist=shoplist #mylist is just another name pointing
         to the same object
del shoplist[0]

print 'shoplist is ',shoplist
print 'mylist is ',mylist
#apple has been removed in the object, so the reference of it
#will print the same list which has no apple.

print'copy by making full slice'
mylist=shoplist[:]
del mylist[0] #remove first item


print 'shoplist is ',shoplist
print 'mylist is ',mylist

output:

shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']

//列表的赋值语句不创建copy,你得通过切片创建拷贝。

五:控制流

1:if语句(if... elif...else:)
eg:
#!/usr/bin/python
#Filename:if.py

number=23
guess=raw_input('enter an integer:)

if guess==number:
    print'bingle!'
elif guess<number:
    print'a little higher~'
else:
    print'a little lower~'

print 'Done'

//Python中没有switch语句,你可以使用if...elif...else完成同样的工作,但在某些场合使用字典(map)会更有效率。

2:while语句

eg:
#!/usr/bin/python
#Filename:while.py

number=23
running=True

while running:
    guess=raw_input('enter an integer:')
   
    if guess==number:
        print r'bingle!\n'
        running=False
    elif guess<number:
        print r'a litter higher~\n'
    else:
        print r'a little lower~\n'

else:
    print'the loop is over~' #useless~
print'Done'

//你可以在while循环中使用一个else从句!

3:for循环
for...in 可以在一个递归对象上递归逐一使用队列的每个item。

eg:

#!/usr/bin/python
#Filename:for.py

for i in range(1,5): #等价于for i in【1,2,3,4】
    print i
else:
    print'loop is over'//useless

output:
1
2
3
4
loop is over

#range()是内建函数,产生一个序列。
#range(2,10,2),表明产生这么一个序列:从2开始,到10终止(不含10),步长为2 ,即【2,4,6,8】,如果没有第三个参数,默认步长为1.

#lese部分是可选的,如果包含else部分,它总是在for结束后执行一次,除非遇到break语句。
#for i in range(0,5)等价于C中 for(int i=0;i<5;++i)


4:break语句
中断/跳出循环
eg:

#!/usr/bin/python
#Filename:break.py

while True:
    s=raw_input()
    if s=='quit'
        break
    print'length of the string is ',len(s)
print 'Done'




5:continue

跳过当前循环的剩余语句,执行下一轮循环。

eg:

#!/usr/bin/python
# Filename: continue.py
while True:
s = raw_input('Enter something longer than 3 chars : ')
if s == 'quit':
break
if len(s) < 3:#len()为内建函数,返回字符串字长。
continue
print 'Input is of sufficient length'



#############################################
        G2
programming is fun
when the work is done
if you wanna make your work also fun:
    use Python!

#############################################