Python基础

source code(.py)-> compiler -> bytecode (.pyc)-> interpreter(pvm)-> processor

过程式编程:以指令为中心,数据服务于指令;
对象式编程:以数据为中心,指令服务于数据;

类(class):

属性
方法

数据类型:

1、数值
2、字符串
3、列表
4、字典
5、元祖
6、文件
7、其它:集合、类、none、布尔型

数值类型:

整数
浮点数
复数

安装python3

#yum install -y python34 python34-devel
#python3
>>> import platform
>>> platform.platform()
'Linux-3.10.0-514.el7.x86_64-x86_64-with-centos-7.3.1611-Core'
>>> platform.system()
'Linux'

第一个py脚本:

#vim first.py
#!/usr/bin/python3
import platform
print(platform.platform())
#chmod +x first.py
#./first.py
Linux-3.10.0-514.el7.x86_64-x86_64-with-centos-7.3.1611-Core

Python IDE:
IDLE
Eclipse和PyDev
PythonWin
Komodo
Wingware
PyCharm

查看数据类型:

>>> a=123
>>> type(a)
<class 'int'>	
>>> a="hello"
>>> type(a)
<class 'str'>

变量命名规则:
1、只能包含字母、数字和下划线,并且不能以数字开头。
2、区分字符大小写。
3、禁止使用保留字,比如 if 等。(python2与python3的保留字不同)

常用的组合数据类型:

1、序列:有序的元素集合,注意是有序的。索引从0开始编号。
	a、列表:[ ],可变对象
	b、元祖:( )
	c、字符串
2、集合
3、映射
	a、字典:多个键值对组成,可变对象

列表

>>> l1 = ["mon","tue","wed"]
>>> l1[0]
'mon'
>>> l1[1]
'tue'

元祖

>>> t1 = ("thu","fri","sat","sun")
>>> t1[0]
'thu'
>>> t1[1]
'fri'

字符串

>>> s = "hello world"
>>> s[0]
'h'
>>> s[1]
'e'

列表内的元素可以嵌套

>>> l2 = [["red","yellow","blue"],["mon","tue","wed"]]
>>> l2[0]
['red', 'yellow', 'blue']
>>> l2[0][0]
'red'

元素类型可以混合

>>> l3 = [123,"abc"]
>>> l3[0]
123
>>> l3[1]
'abc'
>>> l3[1][0]
'a'

逻辑运算

1、身份操作符
	is:判断左边对象引用是否与右边对象引用相同,也可以与None对比。
2、比较操作符
	<、>、<=、>=、!=、==
3、成员操作符
	in、not in
4、逻辑运算符
	and、or、not
	&、|、^

数值运算
+、-、*、/、**、%、//

常见的控制流语句

1、if
2、while
3、for...in
4、try

输入/输出

输出:
	python3:print()函数
	python2:print语句
输入:
	input()
	raw_input()

函数
在python中,使用 def 语句定义函数 。
函数也是对象,可以存储在组合数据类型中,也可以作为参数传递给其他函数。
callable()可用于测试函数是否可调用。
python标准库中拥有众多内置模块,这些模块拥有大量函数。python模块实际上就是包含python代码的py文件。

注释:#
续行:

''':闭合操作符,单一语句跨多行。

字典

>>> d1 = {'name': 'jerry','age': 18,'gender': 'male','title': 'ufo'}
>>> len(d1)
4
>>> d1['name']
'jerry'
>>> d1['age']
18

字典是可变对象,可修改元素赋值

>>> d1['age'] = 21
>>> d1
{'title': 'ufo', 'gender': 'male', 'age': 21, 'name': 'jerry'}

字典支持成员关系判断

>>> 'title' in d1
True

集合

>>> s1 = set('hello')
>>> s1
{'h', 'l', 'o', 'e'}
>>> s2 = set('world')
>>> s2
{'r', 'o', 'w', 'l', 'd'}

浅复制,只复制了指针,而没有复制对象。修改对象会影响所有key。

>>> l1 = [123,456]
>>> l2 = l1
>>> l1.pop()
456
>>> l1
[123]
>>> l2
[123]

深复制,需要使用copy模块

>>> import copy
>>> l3 = copy.deepcopy(l1)
>>> l1
[123]
>>> l3
[123]
>>> l2
[123]
>>> l1.append(567)
>>> l1
[123, 567]
>>> l2
[123, 567]
>>> l3
[123]

这里l2是浅复制,所以修改对象后其value也被修改了。l3是深复制,所有其value没有受影响。

可以使用 del 来删除指定的元素,通过索引编号指定元素位置。

>>> del l2[0:1]
>>> l2
[567]

使用 id() 函数可以查看对象的身份标识,身份标识是唯一的。

>>> id(l1)
139982409294536
>>> id(l2)
139982409294536
>>> id(l3)
139982543522248

这里 l2 是浅复制,id 相同,l3 是深复制,id不同。

每个对象中的元素也有自己的id,且相同的 value 其 id 也相同。

>>> l4 = [123,456]
>>> num1 = 123
>>> id(l4[0])
139982543009952
>>> id(num1)
139982543009952

身份操作运算

>>> l4[0] is num1
True

这里,l4[0] 和 num1 指向相同的元素,其 id 相同,则判断为 True。

有时候,列表打印的出的结果一样,列表 id 却不相同。但是,其引用的相同的元素对象的 id 是相同的,因为有的数据类型是不可变的,不管在哪引用 id 都一样。

三种比较运算:对象值比较、对象身份比较、对象类型比较

>>> l1
[567]
>>> l2
[567]
>>> l3
[123]
>>> l1 == l2
True
>>> l1 is l2
True
>>> type(l1)
<class 'list'>
>>> type(l2)
<class 'list'>
>>> type(l1) is type(l3)
True

python中真和假的含义
非零数字为真,否则为假
非空对象为真,否则为假
None始终为假

if测试

if boolean_expr1:
	suite1
elseif boolean_expr2:
	suite2
...
else:
	else_suite

>>> if l1 is l2:
...             print('same')
... 
same
>>> if l1 is l3:
...             print('same')
... else:
...             print('different')
... 
different

三元表达式

expression1 if boolean_expr else expression2
>>> a=2
>>> b=17
>>> max=a if a>b else b
>>> print(max)
17

while循环

while boolean_expr:
	while_suite
else:
	else_suite

else分支为可选部分。
只要boolean_expr的结果为true,循环就会执行。
boolean_expr的结果为false时终止循环,此时如果有else分支,则会执行else_suite。

>>> i=1
>>> sum=0
>>> while i <= 100:
...     sum+=i
...     i+=1
... else:
...     print(sum)
... 
5050

break:跳出所处的最近层循环。
continue:提前结束本轮循环,进入下一轮循环。
pass:占位语句,当语法需要语句但是还没有任何实用语句可写时使用。
else:只要循环是正常终止,else分支就会执行。在由于break语句、或返回语句、或语法错误导致循环终止时,则else分支不执行。

while boolean_expr1:
	while_suite
	if boolean_expr2: break
	if boolean_expr3: continue
else:
	else_suite

for循环

for expression1 in iterable:
	for_suite
else:
	else_suite

这里的epxpression通常是一个变量序列,一般以元祖的形式给出。
如果以元祖或列表用于expression,则其中的每个数据项都会拆分到表达式的项

>>> T=[(1,2),(3,4),(5,6),(7,8)]
>>> for (a,b) in T:
...     print(a,b)
... 
1 2
3 4
5 6
7 8

>>> l1=list('hello')
>>> l1
['h', 'e', 'l', 'l', 'o']
>>> for i in l1:
...     print(i)
... 
h
e
l
l
o

在python中,for循环比while循环执行速度快。

range():一次性返回连续的整数列表。
xrange():一次生成一个数据元素,相对于range更节约空间。在python3中,已经合并为一个函数range(),功能同xrange()。

与python2不同,在python3中,使用range()不会直接返回一个列表,而是返回一个迭代器。

>>> help(range)
range(stop) -> range object 	可以只给一个整数,则返回一个以0开始的连续整数列表。
range(start, stop[, step]) -> range object 	也可以给一个范围,则以指定的start开始。支持步进。
>>> range(10)
range(0, 10)
>>> for i in range(10):
...     print(i)
... 
0
1
2
3
4
5
6
7
8
9

>>> range(1,11,2) 		取奇数
range(1, 11, 2)
>>> for i in range(1,11,2):
...     print(i)
... 
1
3
5
7
9

zip()
以一个或多个列表为参数,将给定列表中的并排的元素配成元祖,并返回这些元祖的列表。
当参数列表长度不同时,以最短的列表的长度为准。
可用于在for循环中实现并行迭代。

生成元祖列表:这个在pytho2和python3中返回的结果不同,在python3中会返回一个zip对象,而不是直接返回一个列表,这一点与range()类似。

>>> L1=[1,2,3,4,5]
>>> L2=['a','b','c','d','e']
>>> zip(L1,L2)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

>>> L1=[1,2,3,4,5]
>>> L2=['a','b','c','d','e']
>>> zip(L1,L2)
<zip object at 0x7f502f278b08>

这里可以把生成的对象赋值给一个变量,然后用__next__()方法查看其value。

>>> kk=zip(L1,L2)
>>> kk.__next__()
(1, 'a')
>>> kk.__next__()
(2, 'b')
>>> kk.__next__()
(3, 'c')
>>> kk.__next__()
(4, 'd')
>>> kk.__next__()
(5, 'e')
>>> kk.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

生成字典列表:

>>> keys=[1,2,3,4,5,6,7]
>>> values=['mon','tue','wed','thu','fri','sat','sun']
>>> D={} 		先创建一个空字典
>>> for (k,v) in zip(keys,values):D[k]=v
... 
>>> D
{1: 'mon', 2: 'tue', 3: 'wed', 4: 'thu', 5: 'fri', 6: 'sat', 7: 'sun'}

迭代
每次返回自己所包含的一个成员的对象。对象实现了__iter__或__getitem__方法。
可迭代对象:
1、序列:list、str、tuple
2、非序列:dict、file
3、自定义的一些包含__iter____getitem__方法的类。

这里在python2和python3中都会返回对象。

>>> L1=[1,2,3,4,5]
>>> L1.__iter__()
<list_iterator object at 0x7fae4571e748>

迭代器(iterator)
又称游标(cursor),是一种可在容器数据(比如列表等)上实现元素遍历的接口。
迭代器是一种特殊的数据结构,是以对象的形式存在的。

使用 iter() 函数可以从可迭代对象中得到迭代器。
若要实现迭代器,需要在类中定义 __next__() 方法,在python2中是 next()。
要使迭代器指向下一个元素,使用 next() 函数即可。
当没有元素可迭代时,会提示 StopIteration 然后退出。

>>> l1=[1,2,3,4,5]
>>> iter(l1)
<list_iterator object at 0x7fae457033c8>
>>> myiter=iter(l1)
>>> myiter.__next__()
1
>>> myiter.__next__()
2
>>> myiter.__next__()
3
>>> myiter.__next__()
4
>>> myiter.__next__()
5
>>> myiter.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

列表解析
是python迭代机制的一种应用,常用于实现创建新的列表。

[expression for iter_var in iterable]
[expression for iter_var in iterable if condition_expr]
>>> L1=[x**2 for x in range(9)] 		生成0-8的二次方的列表
>>> L1
[0, 1, 4, 9, 16, 25, 36, 49, 64]

>>> L2=[x for x in range(2,101,2)] 		生成2-101以内的所有偶数的列表
>>> L2
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]

>>> L3=[x for x in range(1,101) if x%2==1]		生成1-101以内的所有奇数的列表
>>> L3
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

enumerate()
range偏移索引而非元素,而enumerate可以同时偏移索引和元素。

>>> s='hello'
>>> enumerate(s)
<enumerate object at 0x7fae45721900>
>>> e=enumerate(s)
>>> e.__next__()
(0, 'h')
>>> e.__next__()
(1, 'e')
>>> e.__next__()
(2, 'l')
>>> e.__next__()
(3, 'l')
>>> e.__next__()
(4, 'o')
>>> e.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

生成器
不是真正创建数字列表,而是返回一个生成器对象,此对象在每次计算出一个条目后,把这个条目"产生"(yield)出来。
生成器表达式使用了"惰性计算"或称作"延迟求值"的机制。
序列过长,并且每次只需要获取一个元素时,应当考虑使用生成器表达式而不是列表解析。

(expression for iter_var in iterable)
(expression for iter_var in iterable if condition_expr)
>>> (x**2 for x in range(9))
<generator object <genexpr> at 0x7fae457218b8>
>>> ge=(x**2 for x in range(9))
>>> ge.__next__()
0
>>> ge.__next__()
1
>>> ge.__next__()
4
>>> ge.__next__()
9
>>> ge.__next__()
16
>>> ge.__next__()
25
>>> ge.__next__()
36
>>> ge.__next__()
49
>>> ge.__next__()
64
>>> ge.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
原文地址:https://www.cnblogs.com/keithtt/p/6540633.html