@贰拾贰画生
感谢 简明Python教程
输入输出
输入:raw_input
string = raw_input('Enter something:')
输出:print
s = 'aaa'
i = 1
print string; print 's = %s, i = %d', (s, i)
--------------------------------------------------------
字符串
单引号’ 双引号” 或三引号’’’ “”" 三引号指示一个多行的字符串如
‘’'fdalkjflksajfkl
fdafdsa
fda’''
--------------------------------------------------------
字符串中转义字符 \
自然字符串,指示某些不需要如转义符那样的特别处理的字符串,字符串前加r或R
r”Newlines are indicated by \n"
Unicode字符串:前加u或U
u”This is a Unicode string"
--------------------------------------------------------
级连字符串
两个字符串按字面意义相邻放着
‘What\’s ’ ‘your name?’
会被自动转成
“What’s your name?”
--------------------------------------------------------
多个物理行写一个逻辑行
s = ’This is a string. \
This continues the string.'
print s
输出为:This is a string. This continues the string.
同理
print \
i
等同于
print i
--------------------------------------------------------
#if else 语句
number = 23
guess =int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
print "(but you do not win any prizes!)"
elif guess < number:
print 'No, it is a little higher than that'
else:
print 'No, it is a little lower than that'
print 'Done'
--------------------------------------------------------
# while语句
number =23
running =True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
running =False
elif guess < number:
print 'No, it is a little higher than that'
else:
print 'No, it is a little lower than that'
else:
print 'The while loop is over.'
print 'Done'
--------------------------------------------------------
break 语句
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'
--------------------------------------------------------
continue 语句
continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
if len(s) <3:
continue
print 'Input is of sufficient length'
输出结果为:
Enter something : a
Enter something : 12
Enter something : abc
Input is of sufficient length
Enter something : quit
--------------------------------------------------------
函数用 def 关键字来定义
def printMax(a, b):
if a > b:
print a, ' is maximum'
else:
print b, ' is maximum'
print Max(3,4)
x =5
y =7
print Max(x, y)
输出:
4 is maximum
7 is maximum
--------------------------------------------------------
使用 global 定义全局变量
def func():
global x
print 'x is', x
x = 2
print 'Changed local x to', x
x = 50
func()
print 'Value of x is', x
输出:
x is 50
Changed global x to 2
Value of x is 2
--------------------------------------------------------
可选的默认参数
def say(message, times = 1):
print message * times
say('Hello')
say('World', 5)
输出:
Hello
WorldWorldWorldWorldWorld
注意:只有在形参表末尾的那些参数可以有默认参数值,即你不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参。例如,def func(a, b=5)是有效的,但是def func(a=5, b)是无效的。
--------------------------------------------------------
关键参数
def func(a, b=5, c=10):
print 'a is ', a, ' and b is ', b, ' and c is ', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)
输出:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
--------------------------------------------------------
函数返回
def maximum(x, y):
if x > y:
return x
else:
return y
print maximum(2,3)
输出:
3
注意:没有返回值的return语句等价于return None。None是Python中表示没有任何东西的特殊类型。例如,如果一个变量的值为None,可以表示它没有值。
--------------------------------------------------------
使用DocStrings
def printMax(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
x = int(x)
y = int(y)
if x > y:
print x, 'is maximum'
else:
print y,'is maximum'
print Max(3,5)
print printMax.__doc__
输出:
5 is maximum
Prints the maximum of two numbers.
The two values must be integers.
DocStrings 也适用于模块和类。
--------------------------------------------------------
模块
模块的文件名必须以 .py 为扩展名
使用 sys 模块
import sys
print 'The command line arguments are:'
for i in sys.argv:
print i
print '\n\nThe PYTHONPATH is', sys.path, '\n'
输出
The command line arguments are:
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']
sys模块包含了与Python解释器和它的环境有关的函数。
脚本的名称总是sys.argv列表的第一个参数。所以,在这里,'using_sys.py'是sys.argv[0]、'we'是sys.argv[1]、'are'是sys.argv[2]以及'arguments'是sys.argv[3]
--------------------------------------------------------
字节编译的.pyc文件
输入一个模块相对来说是一个比较费时的事情,所以Python做了一些技巧,以便使输入模块更加快一些。一种方法是创建字节编译的文件,这些文件以.pyc作为扩展名。字节编译的文件与Python变换程序的中间状态有关(是否还记得Python如何工作的介绍?)。当你在下次从别的程序输入这个模块的时候,.pyc文件是十分有用的——它会快得多,因为一部分输入模块所需的处理已经完成了。另外,这些字节编译的文件也是与平台无关的。所以,现在你知道了那些.pyc文件事实上是什么了。
--------------------------------------------------------
from..import语句
如果你想要直接输入argv变量到你的程序中(避免在每次使用它时打sys.),那么你可以使用from sys import argv语句。如果你想要输入所有sys模块使用的名字,那么你可以使用from sys import *语句。这对于所有模块都适用。一般说来,应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突。
--------------------------------------------------------
模块的__name__
每个模块都有一个名称,在模块中可以通过语句来找出模块的名称。这在一个场合特别有用——就如前面所提到的,当一个模块被第一次输入的时候,这个模块的主块将被运行。假如我们只想在程序本身被使用的时候运行主块,而在它被别的模块输入的时候不运行主块,我们该怎么做呢?这可以通过模块的__name__属性完成。
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
输出:
This program is being run by itself
>>> import using_name
I am being imported from another module
--------------------------------------------------------
创建及引用模块
创建自己的模块:
#Filename: mymodule.py
def sayhi():
print 'Hi, this is mymodule speaking.'
version ='0.1'
在与该模块的同等目录下
import mymodule
mymodule.sayhi()
print 'Version ', mymodule.version
输出:
Hi, this is mymodule speaking.
Version 0.1
--------------------------------------------------------
dir() 函数
用来列出模块定义的标识符。标识符有函数、类和变量
如上例,执行
dir(mymodule)
输出:
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'sayhi', 'version']
如果不给 dir 函数传递参数,默认地,它会返回当前模块的属性列表。
--------------------------------------------------------
Python 中有三种内建的数据结构:列表、元组和字典。
--------------------------------------------------------
列表
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have ', len(shoplist), ' items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
print item,
print '\nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist
print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist
print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist
输出:
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']
--------------------------------------------------------
元组
元组和列表十分类似,只不过元组和字符串一样是不可变的,即你不能修改元组。
zoo = ('wolf', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)
new_zoo = ('monkey', 'dolphin', zoo)
print 'Number of animals in the new zoo is', len(new_zoo)
print 'All animals in new zoo are', new_zoo
print 'Animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2]
输出:
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
有0个项目的元组:myempty = ()
有1个项目的元组:singleton = (1, )
--------------------------------------------------------
元组与打印语句
age =22
name = 'Swaroop'
print ' %s is %d years old.’ % (name, age) #此句等同:print name, ‘ is ‘, age, ‘ years old.'
print 'Why is %s playing with that python?' % name
输出:
Swaroop is 22 years old
Why is Swaroop playing with that python?
--------------------------------------------------------
字典
ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}
print "Swaroop's address is %s" % ab['Swaroop']
ab['Guido'] = 'guido@python.org'
del ab['Spammer']
print '\nThere are %d contacts in the address-book\n' % len(ab)
for name, address in ab.items():
print 'Contact %s at %s' % (name, address)
if 'Guido' in ab:
print "\nGuido's address is %s" % ab['Guido']
输出:
Swaroop's address isswaroopch@byteofpython.info
There are 4 contacts in the address-book
Contact Swaroop atswaroopch@byteofpython.info
Contact Matsumoto atmatz@ruby-lang.org
Contact Larry atlarry@wall.org
Contact Guido atguido@python.org
Guido's address isguido@python.org
--------------------------------------------------------
序列
序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。
shoplist = ['apple', 'mango', 'carrot', 'banana']
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[:]
输出:
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']
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[:]
输出:
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
--------------------------------------------------------
参考
当你创建一个对象并给它赋一个变量的时候,这个变量仅仅参考那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。
print 'Simple Assignment'
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
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object
print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0]
print 'shoplist is', shoplist
print 'mylist is', Myles
输出:
Simple Assignment
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']
注意:如果你想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单对象),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都参考同一个对象,那么如果你不小心的话,可能会引来各种麻烦。
--------------------------------------------------------
更多字符串方法
name = 'Swaroop' # This is a string object
if name.startswith('Swa'):
print 'Yes, the string starts with "Swa"'
if 'a' in name:
print 'Yes, it contains the string "a"'
if name.find('war') !=-1: #返回-1表示找不到子字符串
print 'Yes, it contains the string "war"'
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)
输出:
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China
--------------------------------------------------------
类 class
class Person:
population = 0
def __init__(self, name):
self.name = name
print '(Initializing %s)' % self.name
Person.population += 1
def __del__(self):
'''I am dying.'''
print' %s says bye.' % self.name
Person.population -= 1
if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' % Person.population
def sayHi(self):
'''Greeting by the person.
Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name
--------------------------------------------------------
继承
class SchoolMember:
def __init__(self, name):
self.name = name
def tell(self):
print 'Name: ' + self.name
class Teacher(SchoolMember):
def __init__(self, name, salary):
SchoolMember.__init__(self, name)
self.salary = salary
def tell(self):
print 'Salary : %d ' % self.salary
class Student(SchoolMember):
def __init__(self, name, marks):
SchoolMember.__init__(self, name)
self.marks = marks
def tell(self):
print 'Marks : %d' % self.marks
t = Teacher('Chengjie', 10000)
s = Student('Makai', 99)
members = [t, s]
for member in members:
member.tell()
输出:
Salary : 10000
Marks : 99
--------------------------------------------------------
操作文件 file
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.write(poem)
f.close()
f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) ==0:# Zero length indicates EOF
break
print line,
f.close()# close the file
输出:
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
r:读模式
w:写模式
a:追加模式
--------------------------------------------------------
储存器
Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为持久地储存对象。
还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。记住,我们把这两个模块都简称为pickle模块。
import cPickle as p
shoplistfile = 'shoplist.data'
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f)# dump the object to a file
f.close()
del shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist
输出:
['apple', 'mango', 'carrot']
--------------------------------------------------------
异常
基本格式:
try:
fadfdsafdaf
except EOFError:
fdaferewasfsdfas
except:
fdafdafwerwe
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit()
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'
输出:
Enter something—>(#此处输入ctrl + d)
Why did you do an EOF on me?
$ pythontry_except.py
Enter something --> Python is exceptional!
Done
--------------------------------------------------------
使用 raise 引发异常
自定义并异常:
class ShortInputException(Exception):
'''A user-defined exception class.'''
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)
# Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
print 'ShortInputException: The input was of length %d, \
was expecting at least %d'% (x.length, x.atleast)
else:
print 'No exception was raised.'
--------------------------------------------------------
try…finally
finally 后为必定执行语句
--------------------------------------------------------
os模块
这个模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行。一个例子就是使用os.sep可以取代操作系统特定的路径分割符。
下面列出了一些在os模块中比较有用的部分。它们中的大多数都简单明了。
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.existe()函数用来检验给出的路径是否真地存在。
--------------------------------------------------------
特殊的方法
在类中有一些特殊的方法具有特殊的意义,比如__init__和__del__方法,它们的重要性我们已经学习过了。
一般说来,特殊的方法都被用来模仿某个行为。例如,如果你想要为你的类使用x[key]这样的索引操作(就像列表和元组一样),那么你只需要实现__getitem__()方法就可以了。想一下,Python就是对list类这样做的!
下面这个表中列出了一些有用的特殊方法。如果你想要知道所有的特殊方法,你可以在《Python参考手册》中找到一个庞大的列表。
名称说明
__init__(self,...) 这个方法在新建对象恰好要被返回使用之前被调用。
__del__(self) 恰好在对象要被删除之前调用。
__str__(self) 在我们对对象使用print语句或是使用str()的时候调用。
__lt__(self,other) 当使用小于运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法。
__getitem__(self,key) 使用x[key]索引操作符的时候调用。
__len__(self) 对序列对象使用内建的len()函数的时候调用。
--------------------------------------------------------
列表综合
通过列表综合,可以从一个已有的列表导出一个新的列表。例如,你有一个数的列表,而你想要得到一个对应的列表,使其中所有大于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
输出
$ pythonlist_comprehension.py
[6, 8]
--------------------------------------------------------
在函数中接收元组和列表
当要使函数接收元组或字典形式的参数的时候,有一种特殊的方法,它分别使用*和**前缀。这种方法在函数需要获取可变数量的参数的时候特别有用。
>>> def powersum(power, *args):
... '''Return the sum of each argument raised to specified power.'''
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100
由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args中。如果使用的是**前缀,多余的参数则会被认为是一个字典的键/值对。
--------------------------------------------------------
lambda形式
lambda语句被用来创建新的函数对象,并且在运行时返回它们。
#!/usr/bin/python
# Filename:lambda.py
def make_repeater(n):
return lambdas: s*n #可为多参数,如: return lambda s1, s2: s1 + s2 + n
twice = make_repeater(2)
printtwice('word')
printtwice(5)
输出
$ pythonlambda.py
wordword
10
它如何工作
这里,我们使用了make_repeater函数在运行时创建新的函数对象,并且返回它。lambda语句用来创建函数对象。本质上,lambda需要一个参数,后面仅跟单个表达式作为函数体,而表达式的值被这个新建的函数返回。注意,即便是print语句也不能用在lambda形式中,只能使用表达式。
--------------------------------------------------------
exec和eval语句
exec语句用来执行储存在字符串或文件中的Python语句。例如,我们可以在运行时生成一个包含Python代码的字符串,然后使用exec语句执行这些语句。下面是一个简单的例子。
>>> exec 'print "Hello World"'
Hello World
eval语句用来计算存储在字符串中的有效Python表达式。下面是一个简单的例子。
>>> eval('2*3')
6
--------------------------------------------------------
assert语句
assert语句用来声明某个条件是真的。例如,如果你非常确信某个你使用的列表中至少有一个元素,而你想要检验这一点,并且在它非真的时候引发一个错误,那么assert语句是应用在这种情形下的理想语句。当assert语句失败的时候,会引发一个AssertionError。
>>> mylist = ['item']
>>> assert len(mylist) >= 1
>>> mylist.pop()
'item'
>>> 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函数调用的时候返回的内容。
网友评论