且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python [1] 基础理论概述

更新时间:2022-09-16 10:39:16

一、Python运行方式

1、Python有两种运行方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
方式1:
Python解释器环境、交互式的
[root@python ~]# python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help""copyright""credits" or "license" for more information.
>>> print "hello world."
hello world.
 
方式2:
Python程序文件
[root@python ~]# vim hello.py
#!/usr/bin/env python
print "hello world."
 
注意:方式2
程序文件开头指明Python解释器的路径,也有两种指明方式
(1) #!/usr/bin/pyton    
(2) #!/usr/bin/env python  ---> 防止python的执行程序文件不在当前系统环境变量中

二、Python变量、运算符和表达式

1、什么是变量?

1
变量是计算机内存中的一块区域,变量可以存储规定范围内的值,而且值可以改变。

2、变量的命名

1
2
3
4
变量名有字母、数字、下划线组成。
数字不能开头
不可以使用关键字
a   a1  a_  a_1

3、变量的赋值

1
是变量声明和定义的过程

4、变量的重新赋值

1
2
3
4
5
6
>>> str = "hello world"
>>> print str
hello world
>>> str = "Join,hello world."
>>> print str
Join,hello world.

5、变量id

1
2
3
4
5
6
7
8
>>> a = 1
>>> b = 1
>>> id(a)
39404344
>>> id(b)
39404344
结论:
a和b是两个不同的标签但引用的是同一个地址空间上的数据,这就是一个数据可以包含多个标签。

6、运算符和表达式

1
2
3
4
5
6
7
8
6.1 Python运算符
赋值运算符:=、-=、+=       
算数运算符:+ - * / % **      
关系运算符:< <= > >= != ==       
逻辑运算符:and、or、not
           
6.2 表达式
表达式是将不同数据(包括变量、函数)用运算符号将一定规则连接起来的一种式子。

三、Python数据类型

1、单引号、双引号、三引号的区别?

1
2
单引号、双引号、三引号的作用都是一样的,都是用来表示字符串的;
唯一足最大的区别就是三引号中可以***的引用单引号、双引号,并且三引号中的字符串可以换行

2、Python中有哪些数据类型

1
数字、字符串、列表、元组、字典

3、字符串切片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#设定字符串
>> str = 'hello world, welcome to BeiJing.'
 
>>> str[::]
'hello world, welcome to BeiJing.'
>>> str[::1]
'hello world, welcome to BeiJing.'
>>> str[0:5:1]
'hello'
>>> str[0:11:1]
'hello world'
 
>>> str[13:-1:1]
'welcome to BeiJing'
 
>>> str[-1:-len(str):-1]
'.gniJieB ot emoclew ,dlrow olle'
 
结论:
string[start:stop:step]  
string[起始值:结束值:步长] #其中如果步长为正数表示正向切片,如果为负数表示反向切片。

4、序列

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
4.1 什么是序列?
列表、元组和字符串都是序列
序列的两个主要特点是索引操作符和切片操作符
索引操作符让我们可以从序列中抓取一个特定项目
切片操作符让我们能够获取到序列的一个切片,即一部分序列
 
索引同样可以是负数,位置是从序列尾开始计算的
因此,shoplist[-1]表示序列的最后一个元素而shoplist[-2]抓取的是倒数第二个项目
 
 
切片操作符是序列名后跟一个[]方括号,方括号中有一个可选的数字并用冒号分割
注意这与你使用的索引操作符十分相似,记住数是可选的,而冒号是必须的
切片操作符的第一个数,(冒号之前)表示切片开始的位置,
第二个数(冒号之后)表示切片刀哪里结束。如果没有指定第二个数,则python会停止在序列尾。
注意:返回的序列从开始位置开始,刚好在结束位置之前结束。
即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。
     
     
4.2 序列的基本操作
len()   : 求序列长度
+       :连接2个序列
*       :重复序列元组
in      : 判断元素是否在序列中
max()   :返回最大值
min()   :返回最小值
cmp(tuple1,tuple2)      :比较2个的序列值是否相同

5、元组()

1
2
3
4
5
6
7
8
9
元组和列表十分类似,只不过元组和字符串一样是不可变的 即你不能修改元组
元组通过()圆括号中用,逗号分割的项目定义
元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用元组的值不会改变。
             
可以存储一系列值、存储安全性比较高的、不可改变的
 
元组的操作
元组和字符串类型一样属于序列类型,可通过索引和切片操作
元组值亦不可变

6、列表 []

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
list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个序列的项目
列表是可变类型的数据
列表的组成:用[]表示列表,包含了多个以逗号分隔开的数字或字符串
             
列表的操作
取值
切片和索引
list[]
添加
list.append()
list.insert()
删除
del(list)
list.remove(list[])
list.pop()
修改
list[] = x
查找
var in list
统计
list.count()
排序
list.sort()
list.reverse
sorted()

7、字典

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
dict()
字典与列表都比较灵活相对于元组,那么字典和列表又有什么区别呢?
区别:字典是python中唯一的映射类型(哈希表)
             
字典对象是可变的,但是字典的键必须使用不可变对象,并且一个字典中可以使用不同类型的键值
             
keys()或者values()返回键列表或者值列表
items()返回包含键值对的元组
             
创建字典
>>> dir = {'key1':'values1','key2':'values2','key3':'values3'}
>>> dic = {'name':'allentuns','age':24,'tel':'13260071987'}
                 
字典查找/取值
>>> dir['key1']
>>> dic['name']
             
字典的遍历
#遍历列表的key
for in dic
    print r
                     
#遍历列表的values
for in dic
    print dic[r]
                     
字典提供了哪些方法
In [69]: dic.
dic.clear       dic.fromkeys    dic.has_key     dic.iteritems   dic.itervalues  dic.pop         dic.setdefault  dic.values 
dic.copy        dic.get         dic.items       dic.iterkeys    dic.keys        dic.popitem     dic.update 
                         
更新和删除
直接用键值访问更新:内建的update()方法可以将整个字典的内容拷贝到另一个字典中。
                 
del dict1['a'] 删除并且返回值为'a'的元素
注释:del属于系统函数,可以删除任意一个变量
                 
dict.pop('a')  删除并且返回值为'a'的元素
dict1.clear()   删除字典所有元素
del dict1      删除整个字典
             
             
字典的内建函数:
type(),str(),cmp()  (cmp很少用于字典的比较,比较依次是字典的大小,键、值)
                 
工厂函数dict()
例如:
dict(zip('x','y'),(1,2)) 或者 dict(x=1,y=2)
{'y':2,'x':1}
使用字典生成字典比重copy慢,因此这种情况下推荐使用copy()
             
dic.get('address','nihao')  #如果dic字典中不存在address的key,那么就返回字符串nihao

四、Python条件语句、循环语句

1、条件语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if 语句的判断条件可以用
>(大于)、<(小于)、==(等于)、>=(大于等于)、<=(小于等于)、!=(不等于)来表示其关系
 
if 单分支语句
-----------------
if 判断条件:
    statements
else:
    statements
     
     
if多分支语句
------------------
if 判断条件1:
    statements1
elif 判断条件2:
    statements2
elif 判断条件3:
    statements3
else:
    statements4

2、循环语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
while循环
概念:即在某条件下、循环执行某段代码、以处理需要重复处理的相同任务。
while循环的循环判断条件可以是任何表达式,任何非零、或非空(null)的值均为true
while 判断条件:
    执行语句......
     
     
for循环
概念:可以遍历任何序列,如一个列表或者一个字符串。
for interating_var in sequence:
    statements(s)
     
for循环的原理:
如果一个序列包含一个表达式列表,它是第一个执行。然后,该序列中的第一项赋值给迭代变量interating_var。接下来,执行语句块。列表中的每个项目分配到interating_var,代码块被执行,直到整个序列被耗尽。
 
嵌套循环
概念:允许在一个循环体里面嵌入另一个循环。

3、循环控制

1
2
3
4
5
6
break
    在语句块执行过程中终止循环,并且跳出整个循环。
continue
    在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环。
pass 语句
    pass是空语句,是为了保持程序结构的完整性。


五、Python函数

1、函数的作用

1
可以重复使用的,用来实现单一或相关联功能的代码段

2、函数的概述

1
2
3
4
5
6
你可以定义一个由自己想要功能的函数,以下是简单的规则:
1.函数代码块以def关键词开头,后接函数标识符名称和圆括号()。
2.任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。
3.函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
4.函数内容以冒号起始,并且缩进。
5.Return[expression]结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。

3、函数的语法、调用、参数列表

1
2
3
4
5
6
7
8
9
10
11
1. 函数的语法
def function(value):
    statements
 
2. 函数的调用
function(value)
 
3. 函数的参数列表
形参:形式参数、是没有值的       --->  def fun(x)
实参:传递给函数的参数         --->  fun(10)
默认参数:形式参数,设置默认值    --->  def fun(x='25') ---> 顺序是自又向左的

4、函数的局部变量和全局变量

1
2
3
4
5
6
7
8
9
局部变量:
在函数中定义的变量一般只能在该函数内部使用,这些只能在程序的特定部分使用的变量我们称之为局部变量
 
全局变量:
在一个文件顶部定义的变量可以供该文件中的任何函数调用,这些可以为整个程序所使用的变量我们称为全局变量
                 
global语句
global 变量名 ---> 强制声明为全局变量
满足的条件:如果函数没有被调用的话,这样的声明是没有意义的,在函数体为还是没有被定义。
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python
#
str01 = 100
def fun():
    global str02
    str02 = 50
    print str02
                     
fun()
print str01
print str02

5、函数的返回值

1
2
3
4
5
6
return
return的返回值可以是任何类型的:比如字符串、列表都是可以的
一个函数中可以自定义多个return,但是在函数中只会执行一个return,一次return执行结束那么整个函数也就结束了
return只会在一个函数中执行一次,一次执行结束整个函数中止
 
return的返回值就是shell中命令的执行结果而非过程

6、冗余参数

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
#####函数中传递参数总结:字符串、变量、元组、字典等等#####
 
def fun01():
        print "Hello world,welcome to BeiJing."
fun01()
 
def fun02(x):
        print x
fun02("Hello,I am Allentuns.")
 
def fun03(x,y):
        print x,y
        print x + y
fun03(4,10)
 
def fun04(username,age=24):
        print "Username is %s,Age is %s" %(username,age)
fun04("allentuns")
 
def fun05(username,age=24):
        print username,age
fun05(age=20,username="hehe")
 
def fun06(x,y):
        c =     x + y
        return c
fun06(10,21)
xxx = fun06(10,21)
print xxx
 
tt = range(1,5,2)
def fun07(x,y):
        c = x + y
        print c
fun07(*tt)
 
d = {'name':'zhengyansheng','age':'22'}
def fun08(name,age):
        print 'Name is %s,Age is %s' %(name,age)
fun08(**d)
 
d = {'age':'22','name':'zhengyansheng'}
def fun08(name,age):
        print 'Name is %s,Age is %s' %(name,age)
fun08(**d)

六、Python练习

1、流程图

Python [1] 基础理论概述

2、Python代码

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/env python
#Author:Allentuns
#Date:20150119
#codind:utf8
 
import os
import re
 
txl = []
def menu():
        print '''
        1.add
        2.display
        3.search
        4.remove
        0.exit
        '''
        op = raw_input('select op: ')
        return op
 
#def add():
#       name = raw_input('Please input name : ')
#       age = raw_input('Please input age : ')
#       tel = raw_input('Please input tel : ')
#       txl.append([name,age,tel])
 
def add():
        while True:
                name = raw_input('Please input name :').strip()
                if len(name) == 0:
                        print 'no invalid user,please continue.'
                        continue
                else:
                        break
        while True:
                try:
                        age = int(raw_input('Please input age :'))
                except ValueError:
                        print 'invalid age.Please continue.'
                        continue
                else:
                        break
        while True:
         tel = raw_input('please input tel :')
         res = r'^1\d{10}$'
         c = len(re.findall(res,tel))
         if c == 0:
             print 'invalid tel.Please continue'
             continue
         else:
             break
 
        age = str(age)
        txl.append([name,age,tel])
 
def display():
         print 'name\tage\ttel'
         print '+'*25
         for in txl:
                print '%s\t%s\t%s' % tuple(i)
 
def search():
        name = raw_input('Please input name : ')
        print 'name\tage\ttel'
        print '+'*25
        for in txl:
                if i[0] == name:
                        print '%s\t%s\t%s' % tuple(i)
 
def remove():
        name = raw_input('Please input name : ')
        for in txl:
                if i[0] == name:
                        txl.remove(i)
                        write_txl()
 
def get_txl():
        if os.path.exists('txl.db'):
                fp = file('txl.db','r')
                s = fp.read()
                for in s.split('\n'):
                        txl.append(i.split(','))
                fp.close()
                ctxl = len(s)
                return ctxl
        else:
                pass
 
def write_txl():
        tmp = []
        fp = file('txl.db','w')
        for in txl:
                tmp.append(','.join(i))
        str = '\n'.join(tmp)
        fp.write(str)
        fp.close()
 
get_txl()
while True:
        op = menu()
        if op == '1':
                add()
                write_txl()
        elif op == '2':
                display()
        elif op == '3':
                search()
        elif op == '4':
                remove()
        elif op == '0':
                break

*****************************************************************************************

2015-01-21 额外补充

一、list方法的使用

1、list的简单描述

1
2
3
4
5
6
7
Python 列表
什么是列表
list是处理和存放一组数据的列表
用途:购物列表,工资列表,送礼列表
 
语法:
Shoplist = ['car','clothes','iphone']

2、list中常用的方法

1
2
3
In [2]: list.
list.append   list.extend   list.insert   list.pop      list.reverse  
list.count    list.index    list.mro      list.remove   list.sort 

3、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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
In [11]: list.append? //列表追加的用法
Type:       method_descriptor
String Form:<method 'append' of 'list' objects>
Namespace:  Python builtin
Docstring:  L.append(object) -- append object to end //在末尾处添加对象 
*****
In [13]: list.insert? //列表插入的用法
Type:       method_descriptor
String Form:<method 'insert' of 'list' objects>
Namespace:  Python builtin
Docstring:  L.insert(index, object) -- insert object before index   //插入元素在索引前
*****
In [14]: list.count?  //列表统计
Type:       method_descriptor
String Form:<method 'count' of 'list' objects>
Namespace:  Python builtin
Docstring:  L.count(value) -> integer -- return number of occurrences of value    //统计出现这个值的次数
*****
In [15]: list.remove? //列表删除
Type:       method_descriptor
String Form:<method 'remove' of 'list' objects>
Namespace:  Python builtin
Docstring:
L.remove(value) -- remove first occurrence of value.      //删除第一次出现的这个值,没有返回值 (通过值然后删除)
Raises ValueError if the value is not present.      
*****
In [16]: list.pop?        //列表删除
Type:       method_descriptor
String Form:<method 'pop' of 'list' objects>
Namespace:  Python builtin
Docstring:
L.pop([index]) -> item -- remove and return item at index (default last). //通过索引的方式删除 默认从最后一个删除 (通过索引然后删除)
Raises IndexError if list is empty or index is out of range.
*****
In [18]: list.index?  //列表通过value然后确定位置
Type:       method_descriptor
String Form:<method 'index' of 'list' objects>
Namespace:  Python builtin
Docstring:
L.index(value, [start, [stop]]) -> integer -- return first index of value. //返回第一个出现这个值的索引位置
Raises ValueError if the value is not present.
*****
In [20]: list.sort?       //列表排序
Type:       method_descriptor
String Form:<method 'sort' of 'list' objects>
Namespace:  Python builtin
Docstring:
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;     //默认是升序
cmp(x, y) -> -1, 0, 1
*****
In [21]: list.reverse?    //倒序 、反向
Type:       method_descriptor
String Form:<method 'reverse' of 'list' objects>
Namespace:  Python builtin
Docstring:  L.reverse() -- reverse *IN PLACE*                 //倒序、反向排序

4、简单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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
>>> name_list = []      //定义一个空列表
 
>>> len(name_list)        //查看列表的长度
0
>>> type(name_list)       //查看列表的类型
<type 'list'>
 
 
>>> name_list.append('mama')  //向列表中添加元素
>>> name_list         //查看列表中有哪些元素
['mama']
>>> name_list.append('baba')  //继续向列表中添加元素
>>> name_list         //再次查看列表中有哪些元素
['mama''baba']
     
     
>>> name_list.insert(1,'zhengyansheng')   //在索引为1的列表前插入'zhengyansheng'字符串
>>> name_list
['mama''zhengyansheng''baba']     //查看列表元素
     
     
>>> name_list                 //列表中索引是从0开始的
['mama''zhengyansheng''baba']
index:0    index:1     index:2
>>> name_list[1]              //从列表中取出我的名字
'zhengyansheng'
     
>>> name_list[1] = 'Allentuns'      //修改列表某一元素的值是通过索引匹配的方式
>>> name_list
['mama''Allentuns''baba']
     
     
     
>>> name_list.remove('Allentuns')
>>> name_list
['mama''baba']  
     
     
>>> name_list
['mama''baba']
>>> name_list.pop(1)          //通过索引删除列表项
'baba'
>>> name_list
['mama']
     
     
>>> name_list
['baba''zhengyansheng''mama']
>>> name_list.index('baba')       //通过value来确定索引的位置
0
>>> name_list.index('mama')
2
>>> name_list.index('zhengyansheng')
1  

二、判断列表中有没有我想要的值有两种方法

1
2
3
4
5
6
7
8
9
10
>>> name_list
['baba''zhengyansheng''mama']
 
方法1:
>>> name_list.count('zhengyansheng')
1
 
方法2:
>> 'zhengyansheng' in name_list
True

*****************************************************************************************

2015-01-22 额外补充

三、元组和列表区别有哪些?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1、如果元组和列表中只有一个元素的表示方法:
>>> str01 = "Hello world."
>>> list01 = [str01]
>>> type(list01)
<type 'list'>
>>> 
>>> tuple01 = (str01)
>>> type(tuple01)
<type 'str'>
>>> 
>>> tuple02 = (str01,)
>>> type(tuple02)
<type 'tuple'>
结论:单个元素中,列表后面不用跟逗号就可以表示列表,但是元组中后面必须跟逗号,否则就变成了变量的赋值。
 
2、列表是可变类型的数据,而元组是不可变的类型数据:
#查看列表有哪些方法
In [26]: list. 
list.append   list.extend   list.insert   list.pop      list.reverse  
list.count    list.index    list.mro      list.remove   list.sort 
 
#查看元组有哪些方法
In [26]: tuple.
tuple.count  tuple.index  tuple.mro

*****************************************************************************************

2015-01-23 额外补充

四、Python字典

  1. 字典的语法

1
2
3
4
DicName = {
        'key1':'value1',
        'key2':'value2',
    }

2. 查看字典有哪些方法

1
2
3
4
In [53]: dict.
dict.clear       dict.get         dict.iteritems   dict.keys        dict.popitem     dict.values      
dict.copy        dict.has_key     dict.iterkeys    dict.mro         dict.setdefault  
dict.fromkeys    dict.items       dict.itervalues  dict.pop         dict.update  

3. 字典方法的使用案例

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
>>> contact_list
{'mama''13222222222''allentuns''13260071987''hehe''13211111111'}
     
>>> contact_list.keys()               //得到字典的key列表
['mama''allentuns''hehe']
     
>>> contact_list.values()     //得到字典的value列表
['13222222222''13260071987''13211111111']
     
>>> contact_list.items()      //得到字典的key和value以元组的方式显示
[('mama''13222222222'), ('allentuns''13260071987'), ('hehe''13211111111')]  
     
>>> contact_list['baba']='11111111111'    //向字典中添加项
>>> contact_list
{'mama''13222222222''allentuns''13260071987''hehe''13211111111''baba''11111111111'}   
     
>>> contact_list.pop('hehe')      //删除item,默认删除第一个出现的
'13211111111'
>>> contact_list
{'mama''13222222222''allentuns''13260071987''baba''11111111111'}
     
>> contact_list['allentuns'] = '2222222222'        //修改某项对应的value
>>> contact_list
{'mama''13222222222''allentuns''2222222222''baba''11111111111'
     
>>> contact_list
{'mama''13222222222''allentuns''2222222222''baba''11111111111'}
>>> ddd = {'yeye':'11111111112'}   
>>> contact_list.update(ddd)      //dict.update方法更新字典项 类似于添加
>>> contact_list
{'mama''13222222222''allentuns''2222222222''yeye''11111111112''baba''11111111111'}
     
>>> contact_list.has_key('mama')  //查看字典中有没有指定的key
True
>>> 'mama' in contact_list
True

4. 字典遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
方法1:字典的遍历  通过字典的items方法
>>> for key,value in contact_list.items():    
...     print key,value
... 
mama 13222222222
allentuns 2222222222
yeye 11111111112
baba 11111111111
 
方法2:字典的遍历  通过key查找的方法
>>> for in contact_list:
...     print i,contact_list[i]
... 
mama 13222222222
allentuns 2222222222
yeye 11111111112
baba 11111111111



     本文转自zys467754239 51CTO博客,原文链接:http://blog.51cto.com/467754239/1606567,如需转载请自行联系原作者