python-入门篇

python的来源

​ python是著名的“Guido van Rossum”在1989年圣诞节期间开发的编程语言

现在,全世界差不多有600多种编程语言,但流行的编程语言也就那么20来种。如果你听说过TIOBE排行榜,你就能知道编程语言的大致流行程度。tiobe的官方数据链接如下:

https://www.tiobe.com/tiobe-index/

总的来说,这几种编程语言各有千秋。C语言是可以用来编写操作系统的贴近硬件的语言,所以,C语言适合开发那些追求运行速度、充分发挥硬件性能的程序。而Python是用来编写应用程序的高级编程语言。

当你用一种语言开始作真正的软件开发时,你除了编写代码外,还需要很多基本的已经写好的现成的东西,来帮助你加快开发进度。比如说,要编写一个电子邮件客户端,如果先从最底层开始编写网络协议相关的代码,那估计一年半载也开发不出来。高级编程语言通常都会提供一个比较完善的基础代码库,让你能直接调用,比如,针对电子邮件协议的SMTP库,针对桌面环境的GUI库,在这些已有的代码库的基础上开发,一个电子邮件客户端几天就能开发出来。

Python就为我们提供了非常完善的基础代码库,覆盖了网络、文件、GUI、数据库、文本等大量内容,被形象地称作“内置电池(batteries included)”。用Python开发,许多功能不必从零编写,直接使用现成的即可。

除了内置的库外,Python还有大量的第三方库,也就是别人开发的,供你直接使用的东西。当然,如果你开发的代码通过很好的封装,也可以作为第三方库给别人使用。

许多大型网站就是用Python开发的,例如YouTube、Instagram,还有国内的豆瓣。很多大公司,包括Google、Yahoo等,甚至NASA(美国航空航天局)都大量地使用Python。

python 的优点

life is short,you need Python –Bruce Eckel

龟叔给Python的定位是“优雅”、“明确”、“简单”,所以Python程序看上去总是简单易懂,初学者学Python,不但入门容易,而且将来深入下去,可以编写那些非常非常复杂的程序。

总的来说,Python的哲学就是简单优雅,尽量写容易看明白的代码,尽量写少的代码。如果一个资深程序员向你炫耀他写的晦涩难懂、动不动就几万行的代码,你可以尽情地嘲笑他。

那Python适合开发哪些类型的应用呢?

首选是网络应用,包括网站、后台服务等等;

其次是许多日常需要的小工具,包括系统管理员需要的脚本任务等等;

另外就是把其他语言开发的程序再包装起来,方便使用。

Python的缺点

任何编程语言都有缺点,Python也不例外。优点说过了,那Python有哪些缺点呢?

第一个缺点就是运行速度慢,和C程序相比非常慢,因为Python是解释型语言,你的代码在执行时会一行一行地翻译成CPU能理解的机器码,这个翻译过程非常耗时,所以很慢。而C程序是运行前直接编译成CPU能执行的机器码,所以非常快。

但是大量的应用程序不需要这么快的运行速度,因为用户根本感觉不出来。例如开发一个下载MP3的网络应用程序,C程序的运行时间需要0.001秒,而Python程序的运行时间需要0.1秒,慢了100倍,但由于网络更慢,需要等待1秒,你想,用户能感觉到1.001秒和1.1秒的区别吗?这就好比F1赛车和普通的出租车在北京三环路上行驶的道理一样,虽然F1赛车理论时速高达400公里,但由于三环路堵车的时速只有20公里,因此,作为乘客,你感觉的时速永远是20公里。

python交互模式

使用当前系统的命令模式,输入python3即可进入交互模式,输入exit()可退出python交互式模式。
交互式模式可以直接显示代码运行的结果。但是之前输入的代码退出交互式模式后不能存到硬盘中

命令行执行.py文件

命令行模式下,进入要执行的.py文件同目录下,输入python3 文件名即可运行

变量的命名规则(标识符)

变量名只能包含字母,数字和下划线,且不能以数字打头;

变量名不能包含空格;

不能将Python 关键字和函数名作为变量名使用;

慎用小写字母i和大写字母O,容易看成数字1和数字0;

Python 的命名是大小写敏感的,也就是说a和A对于解释器而言,是两个不同的名字;

占位符(place holder)

%d %.2f %.1f %s

%d 表示十进制整数占位符
%.2f 表示浮点数保留到2位小数点后
%.1f 表示浮点数保留到1位小数点后
%s 表示字符串

进制

二进制 (binary)

1
2
3
a = 0b111 #7
#二进制的形式表示7
a = bin(7)

十进制 (decimal)
十六进制 (hexadecimal)

1
2
3
a = 0xff #255
#十六进制的形式表示255
hex(255)

占位符表示进制

1
print("%x" %(255)) #使用16进制的形式表示255

注释

多行注释 “””
单行注释 #

列表 list

list 列表类似Java中的列表list都是类构成

下标的使用如: list[1]、list[-1]

列表的追加如:list.append()

列表的删除如:

del list[x] 直接删除指定索引处的元素
list.pop(x) 弹出指定索引处的元素并返回
list.remove(x) 删除首个指定元素

列表的排序:
list.sort()
列表拷贝
list.copy() 此拷贝不是深层拷贝,如果想要深层拷贝使用copy.deepcopy

数值列表

1
2
3
print("output of range(10):")
for i in range(5):
print(i)

列表的快速生成

1
2
3
matrix = [[0]*8]*10
cubes = [x**3 + 100 for x in range(1,11)]
variables = [x+y for x in 'abc' for y in '0123']

切片(slice)

1
2
3
numbers = [x for x in range(10)]

print("numbers[3:9]:",numbers[3:9])

切片会生成一个新的list返回,并不是直接操作原有的list
切片可以对str类型的数据使用

妙用切片

1
2
3
4
5
6
7
numbers = [x for x in range(10)]

numbersCopy = numbers[:]

numbersReversed = numbers[::-1]
print("numbers[:3:-2] is:",numbers[:3:2])
print("numbers[:3:-2] is:",numbers[:3:-2])

将切片的参数划分为[x:y:z]
当z为正数时 x默认为0,y默认为最后一个元素不包含、
当z为负数时 x默认为最后一个值,y默认为第一个值并且包含

数据类型

元组(tuple)

元组是只读的列表
当只有一个数时需要加,如下

1
print((1,))

byte字节

字节的作用:用来存储数据方便数据的交流,如字节流

字节的存储Python:

little 高位字节存高地址
big 高位字节存低地址

Intel ARM little endian

Motorola big endian

将数据以二进制字节的方式存储

example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import struct
import matplotlib.pyplot as plt

# write
lData = [11,18.234,10.342,3.2342,13]
with open('secondData.dat','wb') as d:
for i in lData:
d.write(struct.pack("<f",i))

# read
data = None
with open('secondData.dat','rb') as d:
data = d.read()

iSampleCount = len(data)//4 #解包的时候是按照4个字节的大小来进行的,所以要求4的倍数,因为Python使用/的结果是flot所以使用//。另外数据的总长度len(data)肯定是能被4整除。
print(len(data))
lCurveData = []
for i in range(iSampleCount):
fValue, = struct.unpack('<f',data[i*4:i*4+4])
lCurveData.append(fValue)

print(lCurveData)
plt.plot(lCurveData)
plt.show()

bytearray

1
2
3
4

buffer = bytearray(b'asdajhskfahs')
buffer[1] = ord('B')
print(buffer)

可以修改的byte 数组

序列 (sequence)

拥有的共同点:都可以使用索引、切片,并且拥有顺序

如 list tuple str byte bytearray

只读类型

int float str bytes boolean tuple

可修改类型

list bytearray dict

名字绑定 (name binding)

概念名词: 名字(name) 对象(object) 绑定(binding)

例子:q=2

解释就是 将 name q 绑定到 object 2 上

== is

1
2
3
4
5
6
7
8
a = 3
b = 3.0

print("a==b:",a==b)

print("a is b:",a is b)

print("a:",id(a),"b:",id(b))

序列解包(sequence unpack)

x,y,z = ‘x’,’y’,’z’
print(x,y,z)

x,y = y,x

print(x,y)

numbers = 1,2,3
print(type(numbers),numbers)

a,b,c = numbers
print(a,b,c)

d,e,f = 4,5,6
print(d,e,f)

g,h,i = ‘789’
print(g,h,i)

j,k,l = b’\x10\x20\x30’
print(j,k,l)

序列解包,首先解包的对象必须是序列,其次解包时两边数据必须保持一致,不然会报错如下
j,k= b’\x10\x20\x30’
number1,number2 = 1,2,3
print(j,k)

解包元素赋值序列
lstr = “Lenoardo di ser Piero Da Vinci”.split()
first,*middle,last = lstr
print(‘first:’,first,”- middle:”,middle,”- last:”,last)
print(‘first id is:’,id(first),”lstr[1] id is:”,id(lstr[1]))

链式赋值

x = y = 2

布尔型

非空即真,非零即真

for 可迭代对象 iterable object

1
2
3
4
s = ""
for x in "asdafasg":
s += x +"-"
print(s)

for else 当for 条件不成立时会触发else 的代码块并执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for x in names:
if x.endswith("Bach"):
print(" I found a Bach:",x)
break
else:
print("No Bach been found.")

matrix = [[x+1+y for x in range(5)] for y in range(6)]

for r in range(6):
for c in range(5):
matrix[r][c] *= 2

for r in matrix:
print(r)

while loop

1
2
3
4
5
6
7
8
sum = i = 0

while i<=100:
sum += i
i += 1
print("sum of (1,2...,100) = ",sum)

names = ["Peter Anderson","Frank Bush","Tom Henry","Jack Lee","Dorothy Henry"]

带下标的遍历 enumerate

1
2
3
4
5
names = ['Tom','Andy','Alex','Dorothy']
print(list(enumerate(names)))

for idx,name in enumerate(names):
print(name +" is %s,id is %s" % (name,idx))

反向遍历

1
2
3
4
5
for x in reversed(names):
print(x)
print(names)
# reversed会生成一个新的序列并将原有的值反向存储
# list本身的reverse会将当前序列的值反向存储

del

1
2
3
4
5
6
x = "Anything"

y = x

del y
print(x)

exec 执行代码无返回

1
2
3
4
5
6
7
exec("print('This  string was print in exec function')")

scopeTemp = {}
scopeTemp['x'] = 30
scopeTemp['y'] = 20
exec("sum = x+y",scopeTemp)
print("sum = ",scopeTemp["sum"])

eval evaluation 评估 执行代码有返回

1
2
r = eval("3+2-5")
print(r)

字符串格式化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import os
sText = "Mary have {} lambs,they are {n1},{n2} and {}.".format(3,'cot',n2='happy',n1='nauty')
print(sText)

dora = {"name":"Dora","id":17,"age":32,"gender":"mate","title":"hello"}
sDoraHtml = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Employee {name}'s information</title>
</head>
<body>

<h1> Employee {name}'s Information</h1>
<table border="1" width="100%">
<tr>
<td>ID:</td>
<td>{id}</td>
<td>Name:</td>
<td>{name}</td>
<td>Age:</td>
<td>{age}</td>
</tr>
<tr>
<td>Gender:</td>
<td>{gender}</td>
<td>Title:</td>
<td>{title}</td>
</tr>
</table>
</body>
</html>
"""
t = open("dora.html",'w')
t.write(sDoraHtml.format_map(dora))
t.close()

os.system("google-chrome dora.html")

dict

key 必须是可哈希类型 hashable Type
可哈希类型 int float str tuple
不可哈希类型 dict list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
doroth = dict(name="Dorothy",id = "10003",age = 26)
print(doroth)

d = dict.fromkeys(['id','name','age'],"unknown")
d1 = {}.fromkeys(['id','name','age'],"unknown")

print(d)
print(d1)



dora = {"name":"Dora","id":17,"age":32,"gender":"mate","title":"hello"}
# print(dora['salary'])
print(dora.get("salary",1000))

sTitle = dora.pop('title')
print(sTitle)
print(dora)


dora = {'id':10003,'age':32,'title':'Salas'}
dora2 = {'id':10004,'title':'CEO','gender':'female'}

dora.update(dora2)
print(dora)

for i in dora:
print(i,end=",")

for i in dora.keys():
print(i,end=",")

for key,value in dora.items():
print(key,"-",value)

函数与抽象

Python实现使用函数的案例

1
2
3
4
5
6
7
8
9
10
11
def costCompute(iStart,iEnd):
"""
计算客户电费,每度电10元
:param iStart: 起始度数
:param iEnd: 最终度数
:return: 电费
"""
iCousume = iEnd - iStart
return iCousume * 10

print(costCompute(100,230))

默认参数(default parameter)

1
2
3
4
5
6
7
def greeting(n,gender="male"):
n = n.title()
s = "Mr " if gender == 'male' else "Miss"
print("Hi,",s,n)

sName = "alan turning"
greeting(sName)

非只读类型的参数

1
2
3
4
5
6
7
8
9
10
def initPerson(person,id,name,age,gender,title):
assert type(person) == dict
person['id'] = id
person['name'] = name
person['age'] = age
person['gender'] = gender
person['title'] = title

dora = {}
initPerson(dora,'10003','dora chen',32,'female','sales')

关键字参数调用

1
2
3
4
5
6
7
8
9
10
def initPerson(person,id,name,age,gender,title):
assert type(person) == dict
person['id'] = id
person['name'] = name
person['age'] = age
person['gender'] = gender
person['title'] = title

initPerson(person=dora,id='10003',name='dora chen',age=32,gender='female',title='sales')
print(dora)

任意数量参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

def myPrint(title,*contents):
print(title,":")
for i in contents:
print("\t",i)

myPrint("Read-only data type:","int","float",'tuple','str','bytes')

def myprint(title,**contents):
print(title,":")
for k,v in contents.items():
print("\t",k+":",v)
myprint("dora",name="Dora chen",age=32)


def initPerson(person,id,name,age,gender,title):
assert type(person) == dict
person['id'] = id
person['name'] = name
person['age'] = age
person['gender'] = gender
person['title'] = title

dora = {}
tDora = ('10003','dora chen',32,'female','sales')
initPerson(dora,*tDora)
print(dora)

dDora = {'id':"10003",'name':'dora chen','age':32,'gender':'female','title':'sales'}
initPerson(dora,**dDora)
print(dora)

python 全局作用域实现方式

1
2
3
4
5
6
7
import pprint
x =1
y =2
scope = vars()
pprint.pprint(scope)
scope['x'] = 3
print(x)

递归 阶乘(factorial)总结不要在大规模的计算中使用递归

1
2
3
4
5
6
7
def factorial(n):
if n==1:
return 1
else:
return n*(factorial(n-1))

print("6!=",factorial(6))

面向对象

程序设计语言
1990年前
结构化编程 structured programming
1990年后
面向对象程序语言 object oriented programming

面向对象关键术语:

类型 type or class

对象 object or instance

属性 attribute or data member

方法 method or function

example:

1
2
3
4
5
6
7
8
9
10
11

from enum import Enum

class Person:
pass

class Gender(Enum):
mate = 1
female = 0

print(range.__doc__)

文件的读写

example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# write
f = open('datafile.txt','w')
f.write("This is a file which is writable in text mode.\n")
f.close()

# read
f = open('datafile.txt','r')
sLine1 = f.readline()
print(sLine1)
f.close()

# 安全使用流的简洁方式
with open('datafile.txt','r') as f:
sLine1 = f.readline()
print(sLine1)

标准输入 标准输出 错误流

example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import sys

iInput = open('standardInput.txt','w')
iInput.write('Alas\n')
iInput.write('27\n')
iInput.close()

sys.stdout = open('standardOut.txt','w')
sys.stdin = open('standardInput.txt','r')
sys.stderr = open('standardError.txt','w')

name = input('Water are you Name?')
age = input('How old are you')
print('This is %s she %s old' %(name,age))

raise Exception("Exception infomatoin")

管道重定向

1
cat title.txt | python wordCount.py

结构化文本文件 ini json

example:

1
2
3
4
5
6
7
8
9
10
import json

dora = "{'name':'Dora','no':'2018173','age':26,'married':false,'scores':[{'c++':76},{'Data structure':99.5}]}"
# write
iDora = open('dora.json','w')
json.dump(dora,iDora)

# read
dora = json.load(open('dora.json','r'))
print(dora)

异常、警告

异常勾子 :当系统发生异常时会执行一个指定的函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import sys,traceback
from datetime import datetime


def userExceptHook(exceptType,value,traceBack):
fError = open('except_error.log', 'w')
traceList = traceback.format_tb(traceBack)
html = str(datetime.now())+'\n'
html += repr(exceptType)+'\n'
html += repr(value) + '\n'
for i in traceList:
html += i+"\n"

print(html,file=sys.stderr)
print(html,file=fError)
fError.close()

sys.excepthook = userExceptHook

sFirst = input("first number")
sSecond = input("second number")
try:
print(int(sFirst)/int(sSecond))
except Exception as e:
raise

类的序列化 迭代器和生成器函数

类的序列化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Fibonacci:

def __init__(self):
self.seq = [0,1,1]
self.maxKey = 1000

def computeTo(self,key):
for i in range(len(self.seq),key +1):
v = self.seq[i-1]+self.seq[i-2]
self.seq.append(v)

def __getitem__(self, item):
if not isinstance(item, int):
raise TypeError('type of item need int')
if not(item>=0 and item<self.maxKey):
raise IndexError("sequence max length is 1000,you's item > max length")
if item>len(self.seq):
self.computeTo(item)
return self.seq[item]

def __setitem__(self, key, value):
if not isinstance(key, int):
raise TypeError('type of key need int')
if not(key>=0 and key<self.maxKey):
raise IndexError("sequence max length is 1000,you's key > max length")
if key > len(self.seq):
self.computeTo(key)
self.seq[key] = value

def __len__(self):
return self.maxKey

f = Fibonacci()
print("f[20]:",f[20])
f[10] = "熊孩子"
for i in range(1,21):
print(f[i],end=",")

print("----------------------------------------------------------------------------------")
class Fibonacci(list):

def __init__(self,*arg):
super().__init__(*arg)
self.iCounter = 0

def __getitem__(self, item):
self.iCounter += 1
return super().__getitem__(item)

f = Fibonacci(range(100))
print('f[20]',f[20])
f[19] = "熊孩子"
print('f[19]',f[19])
print(f)

创建可迭代类

迭代器和序列的对比

迭代器,由于是当系统调用next方法时才会生成相应的数据所以在系统资源占用损耗节省方面优于序列,但是不能像序列那样可以随意指定下标取值,并且只能迭代一次.推荐需要依次获取一次数据时使用

序列,由于系统执行后会在系统内部一次性创建完成序列所以系统资源占用损耗节省方面劣于迭代器,但是它可以获取指定下标的值.推荐在重复或指定获取数据的情况下使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Fibonacci:

def __init__(self,arg):
self.a = 1
self.b = 1
self.index = 0
self.length = arg

def __iter__(self):
return self

def __next__(self):
result = None
if not isinstance(self.index,int):
raise TypeError
elif self.index >= self.length or self.index<0:
raise StopIteration
if self.index in(0,1):
result = 1
else:
result = self.a + self.b
self.a,self.b = self.b,result
self.index += 1

return result
f = Fibonacci(10)
print(list(f))
for i in f:
print(i,end=",")

生成器函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def fibonacciGenerator(len):

if not isinstance(len,int):
raise TypeError

a,b =1,1
for i in range(1,len+1):
if i in (1,2):
yield 1
else:
c = a + b
a,b = b,c
yield c
f = fibonacciGenerator(10)
print(list(f))
for i in f:
print(i,end=",")

f = [i**2 for i in range(10)] #列表推导
f2 = (i**2 for i in range(10))
print(type(f),f)
print(type(f2),list(f))