Python基础(简明Python教程)
参考简明Python教程
基本概念
- 注释符 #
-
基本数据类型
整数、长整数、浮点数(52.3E-4)、复数(-5+4j)
字符串 - 对象
运算符
-
与Java基本一致
运算符
- 运算符优先级
控制流
- if语句
number = 20
guess = int(raw_input('Enter an integer:'))
if guess == numberprint 'true'
elif guess < numberprint 'higher'
else:print 'lower'
- while语句
number = 23
running = Truewhile running:guess = int(raw_input('Enter an integer : '))if guess == number:print 'Congratulations, you guessed it.' running = False # this causes the while loop to stopelif 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.' # Do anything else you want to do hereprint 'Done'
-
for语句
取值为[1,2,3,4]
步长默认为1,与foreach相似
for i in range(1, 5):print i
else:print 'The for loop is over'
- break continue:与Java相似
函数
- 定义函数
def sayHello():print 'Hello World!' # block belonging to the functionsayHello() # call the function
- 通过global语句定义全局变量
def func():global xprint 'x is', xx = 2print 'Changed local x to', xx = 50
func()
print 'Value of x is', x # x变成2
- 默认参数值
def say(message, times = 1):print message * timessay('Hello')
say('World', 5) # 输出WorldWorldWorldWorldWorld
Tip:有默认值的参数必须放在形参表末尾
- 关键参数
- return语句
pass 在python中表示一个空的语句块 -
DocStrings
文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述
使用__doc__(注意双下划线)调用printMax函数的文档字符串属性(属于函数的名称)
def printMax(x, y):'''Prints the maximum of two numbers.The two values must be integers.'''x = int(x) # convert to integers, if possibley = int(y)if x > y:print x, 'is maximum'else:print y, 'is maximum'printMax(3, 5)
print printMax.__doc__
输出:
$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.The two values must be integers.
模块
- sys模块
- 模块的__name__
- dir()函数:用于列出模块定义的标识符,包括函数,类和变量
数据结构
-
列表list
listSample = ['a','b','c'] len(listSample) #长度 listSample.append('d') #添加 listSample.sort() #排序 del listSample[0] #删除,删除后元素自动前移
- 元组
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
Tip:
singleton = (2 , ) 必须在第一个项目后跟一个逗号
-
字典:
键值对,只能用不可变对象(如字符串)作为字母的键
键值对没有顺序
# 'ab' is short for 'a'ddress'b'ookab = { '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']# Adding a key/value pair
ab['Guido'] = 'guido@python.org'# Deleting a key/value pair
del ab['Spammer']print 'nThere are %d contacts in the address-bookn' % len(ab)
for name, address in ab.items():print 'Contact %s at %s' % (name, address)if 'Guido' in ab: # OR ab.has_key('Guido')print "nGuido's address is %s" % ab['Guido']
-
序列:列表、元组、字典都是序列
索引操作符:listSample[0] 可以取得序列中的单个项目,也称为下标操作;可以为负数,即从序列尾开始计算,listSample[-1]是序列的最后一个元素
切片操作符:listSample[1:3],3为终止位置,不输出;listSample[1:]从1到最后 -
参考:创建对象并赋一个变量时,仅仅是那个对象的参考;需要复制的话,需要使用切片操作符拷贝 mylist = shoplist[:]
- 字符串函数
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"'
面向对象的编程
- self:类必须有一个额外的第一个参数名称,惯例名称叫做self
- 类
class Person:pass # An empty blockp = Person()
print p
- 对象的方法
- __init__方法:在类的一个对象被建立时,马上运行,可用于初始化
- 类和对象的方法
Tip:
python中所有类成员都是公共的,所有方法都是有效的;如果数据成员名称以 双下划线前缀 如__privatevar,Python的名称管理体系会有效地把它作为 私有变量
- 继承
输入输出
- 文件
- 存储器 cPickle or pickle