Python(英语发音:/ˈpaɪθən/), 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年末发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具备丰富和强大的类库。它常被昵称为胶水语言,它可以把用其余语言制做的各类模块(尤为是C/C++)很轻松地联结在一块儿。常见的一种应用情形是,使用Python快速生成程序的原型(有时甚至是程序的最终界面),而后对其中有特别要求的部分,用更合适的语言改写,好比3D游戏中的图形渲染模块,性能要求特别高,就能够用C++重写。java
官网:https://www.python.org/python
下载:https://www.python.org/downloads/c++
一:安装时选择加入环境变量shell
二:重启express
三:测试编程
打开cmd,输入:python安全
四:hello world数据结构
1. 使用文本建立以.py后缀的文件,如test.py,输入如下代码(python3的语法):app
print('hellow world');函数
2. 打开cmd,切换到test.py目录,输入如下命令
python test.py
五:基本语法摘要
1:函数
函数经过def定义。def关键字后跟函数的标识符名称,而后跟一对圆括号,括号以内能够包含一些变量名,该行以冒号结尾;接下来是一块语句,即函数体。
def sumOf(a, b): return a + b1).函数形参
函数中的参数名称为‘形参’,调用函数时传递的值为‘实参’
2).局部变量
在函数内定义的变量与函数外具备相同名称的其余变量没有任何关系,即变量名称对于函数来讲是局部的。这称为变量的做用域。
global语句, 为定义在函数外的变量赋值时使用global语句。
def func(): global x print "x is ", x x = 1 x = 3 func() print x3).默认参数
经过使用默认参数可使函数的一些参数是‘可选的’。
def say(msg, times = 1): print msg * times say("peter") say("peter", 3)
注意:只有在形参表末尾的那些参数能够有默认参数值,即不能在声明函数形参的时候,先声明有默认值的形参然后声明没有默认值的形参,只是由于赋给形参的值是根据位置而赋值的。
4).关键参数
若是某个函数有不少参数,而如今只想指定其中的部分,那么能够经过命名为这些参数赋值(称为‘关键参数’)。
优势:没必要担忧参数的顺序,使函数变的更加简单;假设其余参数都有默认值,能够只给咱们想要的那些参数赋值。
def func(a, b=2, c=3): print "a is %s, b is %s, c is %s" % (a, b, c) func(1) #a is 1, b is 2, c is 3 func(1, 5) #a is 1, b is 5, c is 3 func(1, c = 10) #a is 1, b is 2, c is 10 func(c = 20, a = 30) #a is 30, b is 2, c is 20
5).return 语句
return语句用来从一个函数返回,即跳出函数。可从函数返回一个值。
没有返回值的return语句等价于return None。None表示没有任何东西的特殊类型。
6).DocStrings (文档字符串)
def func(): '''This is self-defined function Do nothing''' pass print func.__doc__
2:模块
模块就是一个包含了全部你定义的函数和变量的文件,模块必须以.py为扩展名。模块能够从其余程序中‘输入’(import)以便利用它的功能。
在python程序中导入其余模块使用'import', 所导入的模块必须在sys.path所列的目录中,由于sys.path第一个字符串是空串''即当前目录,因此程序中可导入当前目录的模块。
1).字节编译的.pyc文件
导入模块比较费时,python作了优化,以便导入模块更快些。一种方法是建立字节编译的文件,这些文件以.pyc为扩展名。
pyc是一种二进制文件,是py文件经编译后产生的一种byte code,并且是跨平台的(平台无关)字节码,是有python虚拟机执行的,相似于
java或.net虚拟机的概念。pyc的内容,是跟python的版本相关的,不一样版本编译后的pyc文件是不一样的。
2).from .. import
若是想直接使用其余模块的变量或其余,而不加'模块名+.'前缀,可使用from .. import。
例如想直接使用sys的argv,from sys import argv 或 from sys import *
3).模块的__name__
每一个模块都有一个名称,py文件对应模块名默认为py文件名,也可在py文件中为__name__赋值;若是是__name__,说明这个模块被用户单独运行。
4).dir()函数
dir(sys)返回sys模块的名称列表;若是不提供参数,即dir(),则返回当前模块中定义名称列表。
del -> 删除一个变量/名称,del以后,该变量就不能再使用。
3:数据结构
python有三种内建的数据结构:列表、元组和字典。
1).列表
list是处理一组有序项目的数据结构,列表是可变的数据结构。列表的项目包含在方括号[]中,eg: [1, 2, 3], 空列表[]。判断列表中是否包含某项可使用in, 好比 l = [1, 2, 3]; print 1 in l; #True;支持索引和切片操做;索引时若超出范围,则IndexError;使用函数len()查看长度;使用del能够删除列表中的项,eg: del l[0] # 若是超出范围,则IndexError
list函数以下:
append(value) ---向列表尾添加项value
l = [1, 2, 2]
l.append(3) #[1, 2, 2, 3]
count(value) ---返回列表中值为value的项的个数
l = [1, 2, 2]
print l.count(2) # 2
extend(list2) ---向列表尾添加列表list2
l = [1, 2, 2]
l1 = [10, 20]
l.extend(l1)
print l #[1, 2, 2, 10, 20]
index(value, [start, [stop]]) ---返回列表中第一个出现的值为value的索引,若是没有,则异常 ValueError
l = [1, 2, 2]
a = 4
try:
print l.index(a)
except ValueError, ve:
print "there is no %d in list" % a
insert(i, value) ---向列表i位置插入项vlaue,若是没有i,则添加到列表尾部
l = [1, 2, 2]
l.insert(1, 100)
print l #[1, 100, 2, 2]
l.insert(100, 1000)
print l #[1, 100, 2, 2, 1000]
pop([i]) ---返回i位置项,并从列表中删除;若是不提供参数,则删除最后一个项;若是提供,可是i超出索引范围,则异常IndexError
l = [0, 1, 2, 3, 4, 5]
print l.pop() # 5
print l #[0, 1, 2, 3, 4]
print l.pop(1) #1
print l #[0, 2, 3, 4]
try:
l.pop(100)
except IndexError, ie:
print "index out of range"
remove(value) ---删除列表中第一次出现的value,若是列表中没有vlaue,则异常ValueError
l = [1, 2, 3, 1, 2, 3]
l.remove(2)
print l #[1, 3, 1, 2, 3]
try:
l.remove(10)
except ValueError, ve:
print "there is no 10 in list"
reverse() ---列表反转
l = [1, 2, 3]
l.reverse()
print l #[3, 2, 1]
sort(cmp=None, key=None, reverse=False) ---列表排序
2)元组
tuple和list十分类似,可是tuple是不可变的,即不能修改tuple,元组经过圆括号中用逗号分割的项定义;支持索引和切片操做;可使用 in查看一个元素是否在tuple中。空元组();只含有一个元素的元组("a",) #须要加个逗号
优势:tuple比list速度快;对不须要修改的数据进行‘写保护’,能够是代码更安全
tuple与list能够相互转换,使用内置的函数list()和tuple()。
l = [1, 2, 3]
print l # [1, 2, 3]
t = tuple(l)
print t # (1, 2, 3)
l1 = list(t)
print l1 #[1, 2, 3]
元组最一般的用法是用在打印语句,以下例:
name = "xxxx"
age = 25
print "Name: %s; Age: %d" % (name, age) # Name: xxxx; Age: 25
函数以下:
count(value) ---返回元组中值为value的元素的个数
t = (1, 2, 3, 1, 2, 3)
print t.count(2) # 2
index(value, [start, [stop]]) ---返回列表中第一个出现的值为value的索引,若是没有,则异常 ValueError
t = (1, 2, 3, 1, 2, 3)
print t.index(3) # 2
try:
print t.index(4)
except ValueError, ve:
print "there is no 4 in tuple" # there is no 4 in tuple
3) 字典
字典由键值对组成,键必须是惟一的;eg: d = {key1:value1, key2:value2};空字典用{}表示;字典中的键值对是没有顺序的,若是想要一个特定的顺序,那么使用前须要对它们排序;d[key] = value,若是字典中已有key,则为其赋值为value,不然添加新的键值对key/value;使用del d[key] 能够删除键值对;判断字典中是否有某键,可使用in 或 not in;
d = {}
d["1"] = "one"
d["2"] = "two"
d["3"] = "three"
del d["3"]
for key, value in d.items():
print "%s --> %s" % (key, value)
#1 --> one
#2 --> two
dict函数以下:
clear() ---删除字典中全部元素
d1 = {"1":"one", "2":"two"}
d1.clear()
print d1 # {}
copy() ---返回字典的一个副本(浅复制)
d1 = {"1":"one", "2":"two"}
d2 = d1.copy()
print d2 #{'1': 'one', '2': 'two'}
dict.fromkeys(seq,val=None) ---建立并返回一个新字典,以序列seq中元素作字典的键,val为字典全部键对应的初始值(默认为None)
l = [1, 2, 3]
t = (1, 2, 3)
d3 = {}.fromkeys(l)
print d3 #{1: None, 2: None, 3: None}
d4 = {}.fromkeys(t, "default")
print d4 #{1: 'default', 2: 'default', 3: 'default'}
get(key,[default]) ---返回字典dict中键key对应值,若是字典中不存在此键,则返回default 的值(default默认值为None)
d5 = {1:"one", 2:"two", 3:"three"}
print d5.get(1) #one
print d5.get(5) #None
print d5.get(5, "test") #test
has_key(key) ---判断字典中是否有键key
d6 = {1:"one", 2:"two", 3:"three"}
print d6.has_key(1) #True
print d6.has_key(5) #False
items() ---返回一个包含字典中(键, 值)对元组的列表
d7 = {1:"one", 2:"two", 3:"three"}
for item in d7.items():
print item
#(1, 'one')
#(2, 'two')
#(3, 'three')
for key, value in d7.items():
print "%s -- %s" % (key, value)
#1 -- one
#2 -- two
#3 -- three
keys() ---返回一个包含字典中全部键的列表
d8 = {1:"one", 2:"two", 3:"three"}
for key in d8.keys():
print key
#1
#2
#3
values() ---返回一个包含字典中全部值的列表
d8 = {1:"one", 2:"two", 3:"three"}
for value in d8.values():
print value
#one
#two
#three
pop(key, [default]) ---若字典中key键存在,删除并返回dict[key],若不存在,且未给出default值,引起KeyError异常
d9 = {1:"one", 2:"two", 3:"three"}
print d9.pop(1) #one
print d9 #{2: 'two', 3: 'three'}
print d9.pop(5, None) #None
try:
d9.pop(5) # raise KeyError
except KeyError, ke:
print "KeyError:", ke #KeyError:5
popitem() ---删除任意键值对,并返回该键值对,若是字典为空,则产生异常KeyError
d10 = {1:"one", 2:"two", 3:"three"}
print d10.popitem() #(1, 'one')
print d10 #{2: 'two', 3: 'three'}
setdefault(key,[default]) ---若字典中有key,则返回vlaue值,若没有key,则加上该key,值为default,默认None
d = {1:"one", 2:"two", 3:"three"}
print d.setdefault(1) #one
print d.setdefault(5) #None
print d #{1: 'one', 2: 'two', 3: 'three', 5: None}
print d.setdefault(6, "six") #six
print d #{1: 'one', 2: 'two', 3: 'three', 5: None, 6: 'six'}
update(dict2) ---把dict2的元素加入到dict中去,键字重复时会覆盖dict中的键值
d = {1:"one", 2:"two", 3:"three"}
d2 = {1:"first", 4:"forth"}
d.update(d2)
print d #{1: 'first', 2: 'two', 3: 'three', 4: 'forth'}
viewitems() ---返回一个view对象,(key, value)pair的列表,相似于视图。优势是,若是字典发生变化,view会同步发生变化。在迭代过程当中,字典不容许改变,不然会报异常
d = {1:"one", 2:"two", 3:"three"}
for key, value in d.viewitems():
print "%s - %s" % (key, value)
#1 - one
#2 - two
#3 - three
viewkeys() ---返回一个view对象,key的列表
d = {1:"one", 2:"two", 3:"three"}
for key in d.viewkeys():
print key
#1
#2
#3
viewvalues() ---返回一个view对象,value的列表
d = {1:"one", 2:"two", 3:"three"}
for value in d.viewvalues():
print value
#one
#two
#three
4) 序列
序列类型是指容器内的元素从0开始的索引顺序访问,一次能够访问一个或者多个元素;列表、元组和字符串都是序列;序列的两个主要特色是索引操做符和切片操做符;索引能够获得特定元素;切片能够获得部分序列;
numbers = ["zero", "one", "two", "three", "four"]
print numbers[1] # one
print numbers[-1] # four
#print numbers[5] # raise IndexError
print numbers[:] # ['zero', 'one', 'two', 'three', 'four']
print numbers[3:] # ['three', 'four']
print numbers[:2] # ['zero', 'one']
print numbers[2:4] # ['two', 'three']
print numbers[1:-1] # ['one', 'two', 'three']
切片操做符中的第一个数(冒号以前)表示切片开始的位置,第二个数(冒号以后)表示切片到哪里结束。 若是不指定第一个数,Python就从序列首开始。若是没有指定第二个数,则Python会中止在序列尾。 注意,返回的序列从开始位置 开始 ,恰好在结束位置以前 结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。 能够用负数作切片。负数用在从序列尾开始计算的位置。
4:面向对象编程
python支持面向对象编程;类和对象是面向对象编程的两个主要方面,类建立一个新的类型,对象是这个类的实例。
对象可使用普通的属于对象的变量存储数据,属于对象或类的变量被称为域;对象也可使用属于类的函数,这样的函数称为类的方法;域和方法能够合称为类的属性。
域有两种类型--属于实例的或属于类自己;它们分别被称为实例变量和类变量。
类使用关键字class建立,类的域和方法被列在一个缩进块中。
类的方法必须有一个额外的第一个参数,可是在调用时不为这个参数赋值,这个特殊变量指对象自己,按照惯例它的名称是self,相似C#中的this。
class Animal:
pass #empty block
__init__方法 在类的一个对象被建立时调用该方法;至关于c++中的构造函数。
__del__方法 在类的对象被销毁时调用该方法;至关于c++中的析构函数。在使用del删除一个对象时也就调用__del__方法。
Python中全部的类成员(包括数据成员)都是public的;只有一个例外,若是使用的数据成员以双下划线为前缀,则为私有变量。
class Person: Count = 0 def __init__(self, name, age): Person.Count += 1 self.name = name self.__age = age p = Person("peter", 25) p1 = Person("john", 20) print Person.Count #2 print p.name #peter print p.__age #AttributeError: Person instance has no attribute '__age'继承:为了使用继承,基类的名称做为一个元组跟在类名称的后面;python支持多重继承。下面是一个关于继承的例子:
class SchoolMember: '''Represent any school member.''' def __init__(self, name, age): self.name = name self.age = age print "Initializing a school member." def tell(self): '''Tell my details''' print "Name: %s, Age: %s, " % (self.name, self.age), class Teacher(SchoolMember): '''Represent a teacher.''' def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary print "Initializing a teacher" def tell(self): SchoolMember.tell(self) print "Salary: %d" % self.salary class Student(SchoolMember): '''Represent a student.''' def __init__(self, name, age, marks): SchoolMember.__init__(self, name, age) self.marks = marks print "Initializing a student" def tell(self): SchoolMember.tell(self) print "Marks: %d" % self.marks print SchoolMember.__doc__ print Teacher.__doc__ print Student.__doc__ t = Teacher("Mr. Li", 30, 9000) s = Student("Peter", 25, 90) members = [t, s] for m in members: m.tell()
5:输入/输出
程序与用户的交互须要使用输入/输出,主要包括控制台和文件;对于控制台可使用raw_input和print,也可以使用str类。raw_input(xxx)输入xxx而后读取用户的输入并返回。
1). 文件输入/输出
可使用file类打开一个文件,使用file的read、readline和write来恰当的读写文件。对文件读写能力取决于打开文件时使用的模式,经常使用模式有读模式("r")、写模式("w")、追加模式("a"),文件操做以后须要调用close方法来关闭文件。
test = '''\ This is a program about file I/O. Author: Peter Zhange Date: 2011/12/25 ''' f = file("test.txt", "w") # open for writing, the file will be created if the file doesn't exist f.write(test) # write text to file f.close() # close the file f = file("test.txt") # if no mode is specified, the default mode is readonly. while True: line = f.readline() if len(line) == 0: # zero length indicates the EOF of the file break print line, f.close()
2) 存储器
python提供一个标准的模块,成为pickle,使用它能够在一个文件中存储任何python对象,以后能够完整的取出来,这被称为持久地存储对象;还有另一个模块成为cPickle,它的功能和pickle彻底同样,只不过它是用c写的,要比pickle速度快(大约快1000倍)。
import cPickle datafile = "data.data" namelist = ["peter", "john", "king"] f = file(datafile, "w") cPickle.dump(namelist, f) f.close() del namelist f = file(datafile) storednamelist = cPickle.load(f) print storednamelist #['peter', 'john', 'king']
6:异常
当程序中出现某些异常的情况时,异常就发生了。python中可使用try ... except 处理。
try: print 1/0 except ZeroDivisionError, e: print e except: print "error or exception occurred." #integer division or modulo by zero
7:Python标准库
Python标准库是随Pthon附带安装的,包含了大量极其有用的模块。
1)sys模块 sys模块包含系统对应的功能
sys.argv ---包含命令行参数,第一个参数是py的文件名
sys.platform ---返回平台类型
sys.exit([status]) ---退出程序,可选的status(范围:0-127):0表示正常退出,其余表示不正常,可抛异常事件供捕获
sys.path ---程序中导入模块对应的文件必须放在sys.path包含的目录中,使用sys.path.append添加本身的模块路径
sys.modules ---This is a dictionary that maps module names to modules which have already been loaded
sys.stdin,sys.stdout,sys.stderr ---包含与标准I/O 流对应的流对象
2) 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.sep 操做系统特定的路径分割符
os.path.split() 函数返回一个路径的目录名和文件名
os.path.isfile() 和os.path.isdir()函数分别检验给出的路径是一个文件仍是目录
os.path.existe() 函数用来检验给出的路径是否真地存在
8:其它
1)lambda
lambda语句被用来建立新的函数对象,并在运行时返回它们。lambda须要一个参数,后面仅跟单个表达式做为函数体,而表达式的值被这个
新建的函数返回。 注意,即使是print语句也不能用在lambda形式中,只能使用表达式。 func = lambda s: s * 3 print func("peter ") #peter peter peter func2 = lambda a, b: a * b print func2(2, 3) #6 2) exec/eval exec语句用来执行储存在字符串或文件中的Python语句;eval语句用来计算存储在字符串中的有效Python表达式。 cmd = "print 'hello world'" exec cmd #hello world expression = "10 * 2 + 5" print eval(expression) #25 3)assert assert语句用来断言某个条件是真的,而且在它非真的时候引起一个错误--AssertionError。 flag = True assert flag == True try: assert flag == False except AssertionError, err: print "failed" else: print "pass" 4) repr函数 repr函数用来取得对象的规范字符串表示。反引号(也称转换符)能够完成相同的功能。 注意,在大多数时候有eval(repr(object)) == object。 能够经过定义类的__repr__方法来控制对象在被repr函数调用的时候返回的内容。 arr = [1, 2, 3] print `arr` #[1, 2, 3] print repr(arr) #[1, 2, 3]