star870126 发表于 2017-4-23 10:54:45

Python语言入门

  第1章    Python语言入门

1.1    HelloWorld

print 'helloworld'
   

1.2    Python数学计算

print 'helloworld'
print 3 + 5
x = 2 ** 2.5 #次方
y = 0
print x, y
from math import * #引入math包
print sqrt(3.0)
print log10(2)
print sin(pi / 3)
   


1.3    斐波那契数列

a, b = 0, 1
while b < 1000:
print b,
a, b = b, a + b

   

第2章    数据类型

2.1    数字

1、    Python支持的数字类型包括:浮点数、整数、长整数等。

2、    算数运算符包括:+、-、*、/、%等。

3、    负号运算符 –。

4、    位运算符 <<、>>、&、^等。


2.2    字符串

1、    单引号

print 'this is a "single-quoted" string,\n don\'t you like it?'
   2、    双引号

print "this is a 'double-quoted' string"
   3、    三引号

print '''this is a triply-quoted string
字串中可以換行, 也可以用單引號和雙引號'''
   

注:使用三引号字符可以换行,并可以添加单引号和双引号


2.2.1    字符处理

s1 = 'Hello'
s2 = 'World'
print s1 + ',' + s2 #重复打印10个*
print '*' * 10 #重复打印10个*
print 'Hello,World!'#取char
for c in 'hello,world!':print c #循环查询char
print 'world' in 'hello,world!' #判断字符串是否包含子串,返回true/false
print 'Hello,World!' #类似java的substring()
print len('Hello,World!') #字符串长度
n = 10
print '学生人数为%d' % n #格式化字符串
   



2.3    List

m =
m.append(3) #添加一个元素
m.extend() #添加一批元素
del m #删除元素
m = -1 #换掉一个元素
m.insert(-1, 3.5) #插入元素参数1:位置,参数2为元素
m = #换掉一批元素
m.sort() #排序
m.reverse() #翻转
m.len() #长度
listone =
listtwo =
print listtwo #输出结果为6,8
#为满足条件(if i > 2)的数指定了一个操作(2*i)
   



2.4    字典Directory

prices = { 'apple': 7.5, 'orange': 4.5, 'banana': 2}
prices['orange'] # 根据键获值
prices.has_key('tomato')
prices.keys() # 获取键集合
prices['guava'] = 6.7 # 添加元素
   


第3章    流程控制

3.1    流程控制

a = 'wangtong'
if a == 'wang':
print '[%s]' % a
elif not a == 'tong': #没有或者有多个
print '[%s]' % a
else:
print '[%s]' % a
   

3.2    逻辑表达式

a, b = 5, 1
def func(x):
print 'x=%s in func' % x
return 1
print a == 5 or func(a) #先判断a=5、再判断func(a)、最后是or
print a > b and func(b) #判断a>b、func(b)、最后and
   

?    逻辑非 not、和 and 、或 or

?    在 in 、 不在 not in

?    比较运算符: 相等 == 不相等 != 大於 > 小於 < 不小於 >= 不大於 <=

可串接: 如 a < b < c != d > g 即等同于 a < b and b < c and c != d and d > g

?    优先順序: 在、不在 > 比较 > 非 > 和 > 或


3.3    循环

3.3.1    For循环

array = ['apple', 'tangerine', 'banana']
print array
for fruit in array: #for循环
print fruit, len(fruit)
if fruit > 'p':
break
3.3.2    For分叉
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n / x
break
else:# not for "if", but for end-of-for-loop
print n, 'is a prime number'
   


?    break: 跳出循环

?    continue: 略过区块的以下部分、从循环的下一次继续

?    else: 在循环走到底时执行


3.3.3    For小技巧

3.3.3.1    遍历字典

prices = { 'apple': 7.5, 'orange': 4.5, 'banana': 2}
for stuff, price in prices.items():
print stuff, '价格是', price
  

3.3.3.2    列出序列索引

prices = { 'apple': 7.5, 'orange': 4.5, 'banana': 2}
m = prices.keys()
m.sort()
for i, v in enumerate(m):
print i, v

   

输出结果:

0 apple

1 banana

2 orange


3.3.3.3    同时循环2个序列

questions = [ 'name' , 'quest' , 'favorite color' ]
answers = [ 'lancelot' , 'the holy grail' , 'blue']
for q, a in zip(questions, answers):
print 'What is your %s? It is %s.' % (q, a)
   


3.3.4    While循环

i = 7
while i > 0:
print i
i = i -1
   


3.3.5    Range范围函数

print range(10) #0 - 10 循环10次
print range(3, 6) # 包括 3, 不包括 6
print range(2, 8, 2)# 每步加 2
m = #(list comprehension)
print m
for i in range(len(m)):
print i, m
   



第4章    函数

4.1    函数基础

def distance(v0,a,t):
return v0*t + a/2.0 * t*t
print distance(1, 2, 3)
   


4.2    预设参数值

def eat(maxprice, lunch='chickenrice', soup='no'):
print 'will eat', lunch, 'for lunch with', soup, 'soup for less than', maxprice
eat(150, '天丼', '味噌')
eat(130, '天丼')
eat(130, soup='羅宋')
eat(150, soup='羅宋', lunch='pasta')
   

在定义函数时: 有预设的参数必须在位置参数的后面

4.3    DocString

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__ #使用__doc__实现docString 实现打印文档字符串
   


输出结果:

5 is maximum

Prints the maximum of two numbers.

    The two values must be integers.


第5章    模块

5.1    使用SYS模块

import sys#引入sys模块,sys模块包含了与Python解释器和它的环境有关的函数
print 'The command line arguments are:'
for i in sys.argv:
print i
print '\n\nThe PYTHONPATH is', sys.path, '\n'
   


5.2    From …import

from math import * #引入math包

注:从代码可读性考虑,尽量避免使用from…import方式导入模块,推荐使用import方式

5.3    模块的__name__

if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
   



5.4    创建模块

def sayhi():
print 'Hi, this is mymodule speaking.'
version = '0.1'
   



import module #导入模块
module.sayhi() #调用模块的方法
print 'Version', module.version
   


5.5    Dir函数

可以使用内建的dir()来列出模块定义的标识符。标识符有函数、类和变量。

当你为dir()提供一个模块名的时候,它返回模块定义的名称列表。如果不提供参数,它返回当前模块中定义的名称列表。


import sys
print dir(sys) # get list of attributes for sys module
   


第6章    面向对象编程

6.1    Self

在Python的Self相当于Java的this指针。

6.2    Class

class Person:
pass # An empty block
p = Person()
print p # 返回结果为<__main__.Person instance at 1>
   

6.3    __Init__方法

注:__Init__方法就是Python的构造器,用于初始化值和对象

class Person:
def __init__(self, name): #初始化方法
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
p = Person('Swaroop') #实例化
p.sayHi()
   


6.4    类与对象方法

类的变量:由一个类的所有对象(实例)共享使用。只有一个类变量的拷贝,所以

class Person:
'''Represents a person.'''
population = 0 #类变量
def __init__(self, name):
'''Initializes the person's data.'''
self.name = name
print '(Initializing %s)' % self.name
#When this person is created, he/she adds to the population
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
def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
   当某个对象对类的变量做了改动的时候,这个改动会反映到所有其他的实例上。

对象的变量:由类的每个对象/实例拥有。因此每个对象有自己对这个域的一份拷贝,即它们不是共享的,在同一个类的不同实例中,虽然对象的变量有相同的名称,但是是互不相关的。



注:Python中所有的类成员(包括数据成员)都是 公共的 ,所有的方法都是有效的 。

6.5    继承

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): #继承自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 =
for member in members:
member.tell() # works for both Teachers and Students
   

第7章    输入与输出

7.1    文件

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = file('poem.txt', 'w') # open for writing
f.write(poem) # write text to file
f.close() # close the file
f = file('poem.txt')
# if no mode is specified,read mode is assumed by default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print line,
# Notice comma to avoid automatic newline added by Python
f.close() # close the file
   

7.2    存储器

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

另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。

注:类似于Java的串行化和反串行化

import cPickle as p
#import pickle as p
shoplistfile = 'shoplist.data'
# the name of the file where we will store the object
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 # remove the shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist
   

第8章    异常

8.1    Try/Exception

import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
print 'Done'
   


8.2    引发异常 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.'
   


注:类似于Java的throw抛出异常


8.3    Try/Exception/Finally

import time
try:
f = file('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,
finally:
f.close()
print 'Cleaning up...closed the file'
   


第9章    Python标准库

9.1    Sys模块

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

import sys
def readfile(filename):
'''Print a file to the standard output.'''
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line, # notice comma
f.close()
# Script starts from here
if len(sys.argv) < 2:
print 'No action specified.'
sys.exit()
if sys.argv.startswith('--'):
option = sys.argv
# fetch sys.argv but without the first two characters
if option == 'version':
print 'Version 1.2'
elif option == 'help':
print '''\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help    : Display this help'''
else:
print 'Unknown option.'
sys.exit()
else:
for filename in sys.argv:
readfile(filename)
   

9.2    OS模块

这个模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行。


常用的函数如下:
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()函数返回一个路径的目录名和文件名。



第10章    Python常用技巧

10.1    特殊方法
__init__(self,...) 这个方法在新建对象恰好要被返回使用之前被调用。

__del__(self) 恰好在对象要被删除之前调用。

__str__(self) 在我们对对象使用print语句或是使用str()的时候调用。

__lt__(self,other) 当使用 小于 运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法。

__getitem__(self,key) 使用x索引操作符的时候调用。

__len__(self) 对序列对象使用内建的len()函数的时候调用。



10.2    Lambda形式

lambda语句被用来创建新的函数对象,并且在运行时返回它们。个人感觉lambda有点像函数指针。

def make_repeater(n):
return lambda s: s * n
twice = make_repeater(2)#将make_repeater赋值给变量twice
print twice('word') #调用make_reoeater函数
print twice(5)
   


10.3    Exec/Eval

exec语句用来执行储存在字符串或文件中的Python语句。

eval语句用来计算存储在字符串中的有效Python表达式。

exec 'print "Hello World"'
eval ('2*3')

 
页: [1]
查看完整版本: Python语言入门