Python初学笔记


<>

以下分三部分来从感性认识到理性命令代码测试来逐步掌握和熟悉Python脚本;重要的是第三部分,把第三部分中每一条命令,每一个函数,都要亲自测试并显示正确结果,运用熟练就ok!

==========================================================

第一部分:当前python应用实例

google web爬虫,搜索引擎

yahoo, 管理讨论组

youtobe, 分享服务

豆瓣网的前台+后台+服务器都用的是python

第二部分:Python概念总体介绍

定位:解释性的,面向对象的带有动态语义的程序设计语言

python特性

脚本语言

高阶动态编程语言

简单易学

解释性&编译性:不需要变异成二进制,但是需要解释器, 也可以进行编译,速度更快

面向对象:及支持面向过程编程又支持面向对象的编程

可扩展性挤可嵌入性,可以嵌入到c/c++程序,提供脚本功能,部分程序也可以用c编写

可移植性:所有程序无需任何修改即可运行在任何平台

丰富的库:密码系统,GUI, TK,文档生成,单元测试,线程,CGI, 电子邮件

其他高质量库:wxPython, Twisted, Python图像库等等

自动化的内存管理

免费,开源

和其它语言结合开发快,又叫胶水语言

认识文件类型三种形式:

1、源代码: 以.py为扩展名,有python程序解释,不需要编译

2、字节代码:编译后生成扩展名为.pyc的文件

import py_compile

py_compile.compile("hello.py")

3、优化代码:经过优化的源文件, 扩展名为.pyo

以上三种均可直接运行

第三部分:Python语言命令和代码的执行测试

1.py

print("hello, world")

运行 python 1.py

==> hello, world

2.py

import py_compile

py_compile.compile('1.py')

生成文件__pycache__/1.cpython-33.pyc

运行 python 1.cpython-33.pyc

==> hello, world

生成优化代码:

运行 python -O -m py_compile 1.py

生成文件__pycache__/1.cpython-33.pyo

运行 python 1.cpython-33.pyo

==> hello, world

python变量

===========================================

>>a1 = 123

>>a2 = 123

>>id(a1)

505912912

>>id(a2)

505912912

于c语言不同,c语言给变量名开辟空间,存放数值,python则相反,数值是存在内存中的

不同变量可以指向同一地址空间的数值

python运算符&表达式

=============================================

赋值运算符

-----------------------

= += -= *= /= %=

算数运算符

-----------------------

+ - * / //(整数除法) %(求余) **(求幂)

>> 4/3

1.33333333333333

>> 4//3

1

关系运算符

-----------------------

< > <= >= != ==

>> a = 1

>> b = 1.0

>> a == b

true

>> a = "hello"

>> b = "hello"

>> a == b

true

逻辑运算符

------------------------

and or not

优先级(低到高)

================================

或 or

与 and

非 not

成员:in, not in

同一性:is ,is not

< , <=, >, >=, !=, ==

按位或 |

按位异或 ^

按位与 &

移位 << , >>

+, -

*, /, %

正负号 +x, -x

按位翻转 ~x

指数 **

数据类型

=======================

数字类型

2.x版本中分为:整型,长整型,浮点型,复数型

3.x版本中氛围:整型,浮点型,复数型

可以用type函数查看类型

>> a = 111

>> type(a)

int

>> a = 1.23

>> type(a)

float

>> a = 12j

>> type(a)

complex

字符串类型

>> "let's go" #正确

>> 'let's go' #错误

转义

>> a = "let's \"go\""

>> print(a)

let's "go"

换行 \n

不使用换行,使用三重引号 ''' xxxxxxx '''

>> str = 'abc'

>> str[0]

a

>> str = "abc"

>> str[0]

a

切片&索引 操作:

>> a = "123456"

>> a[1:4]

1234

>> a[2:]

3456

>> a[:4]

1234

>> a[-1]

6

>> a[::1] 间隔0个一取

123456

>> a[::2] 间隔1个一取

135

>> a[:]

123456

>> a[::]

123456

序列

列表,元组,和字符串都是序列

序列的两个主要特点:索引操作符和切片操作符

序列的基本操作:

len()

>> len("abcdef")

*

>> 5*"a"

+

>> "abc" + "bcd"

in

>> "a" in "abc"

max()

>> max("adfe")

f

min()

>> min("dfa")

a

cmp(tuple1, tuple2)

tuple1> tuple2 ==> 1

tuple1< tuple2 ==> -1

tuple1 = tuple2 ==> 0

cmp("abc", "123") ?

cmp 在3.x版本中不存在

元组

元组和列表十分相似,只不过元组和字符串一样是不可变的,即不能修改

通常用在使用语句或者用户定义的函数,能够安全的采用一组值的时候

创建元组()

空元组 a = ()

含有单个元素的元组 a = ("a",)

一般的元组 a = ("a", "b")

>> a = ()

>> b = (2,)

>> c = (1,2)

>> type(a) ==> tuple

>> type(b) ==> tuple

>> type(c) ==> tuple

错误的写法

>> d = (2)

>> type(d) ==> int

>> d = ("ss")

>> type(d) ==> str

元组的值不能修改

>> a = (2,3)

>> a[1] = 4 #报错TypeError: 'tuple' object does not support item assignment

赋值

>> name,age,sex = ("zhang", 20, "man")

>> name ==> "zhang"

>> age ==> 20

>> sex ==> "man"

#列表list[]

列表元素可变

>> a = [1]

>> type(a) ==> list

基本操作

索引 list[index]

切片 list[:]

添加 list.append()

查找 var in list

删除 list.remove() #删除第一个出现的元素

>> a = [1,2,3,2]

>> a.remove(2) ==> [1,3,2]

系统方法del

>> del(a[0]) ==> [3,2]

注意:列表重新赋值后,地址空间不变

>> list = [1, 3]

>> id(list) => 85445

>> list[0] = 2

>> id(list) => 85445

条件表达式

python使用缩进作为其语言的分组方法

如果缩进不统一,程序报错

if 1 > 2:

print("ok")

print("ok")

print("xx")

print("no")

==> no

if 1 > 2:

print("ok")

print("ok")

print("xx")

print("no")

==> IndentationError: unindent does not match any outer indentation level

x = 99

if x > 90:

print("A")

elif x > 80:

print("B")

elif x > 70:

print("C")

else:

print("D")

取反,用not,不能用!

if not 0

print("OK")

循环遍历:

for i in range(10):

print("hello ,world")

for i in [1,3,4,5,5]:

print(i)

for i in range(1,10):

print(i)

==> 1,2,3..10

for i in range(1, 10, 2):

print(i)

==> 1,3,5,7,9

列表的遍历:

d = {2:333, 4:444, 5:666}

for k,v in d.items():

print(k)

print(v)

else:

print("ending")

结果==>

2

333

4

444

5

666

ending

-------------------------------

比较特殊的,python中for循环可以接else,当循环正常执行完毕后

执行else中的语句,如果循环中断,则不会执行else的语句

d = {1:333, 2:444, 3:666, 4: 444, 5: 777}

for k,v in d.items():

if k == 2:

break

else:

print(k)

print(v)

else:

print("ending")

结果==>

1

333

pass 代码桩,什么也不做

continue 继续

exit() 退出程序

---------------------------------------

d = {1:333, 2:444, 3:666, 4: 444, 5: 777}

for k,v in d.items():

if k == 3:

break

if k == 2:

pass

continue

if k == 5:

exit()

else:

print(k)

print(v)

else:

print("ending")

while 循环:

--------------------------------------------

$ cat while.py

当while条件为false时,才会执行else中的语句

x = ""

while x != "q":

print("hello")

x = input("input something, q for quit: ")

if not x :

break

else:

print("ending")

函数:

------------------------------

a = 2

b = 3

def add():

c=a+b

print(c)

add()

==> 5

这个有点不安全吧,要是函数体中得变量不小心和函数外的变量重名,那不是麻烦了?

def new_add(x, y):

z = x + y

print(z)

add()

new_add(3,4)

传参

----------------------------------

def add(x = 3, y = 4):

c = x + y

print(c)

add()

add(y = 5) #可以单独传参,但是如果x没有默认值就不行了

全局变量

-------------------------

$ cat global.py

x = "global var"

def change():

x = 100

print(x)

==> "global var"

------------------------------

$ cat global.py

x = "global var"

def change():

global x

x = 100

change() #执行了change()方法以后,global x ,相当于给x重新赋值了

print(x)

==> 100

元组作为参数

-------------------------

$ cat function1.py

def add(x, y):

print("%s : %s" % (x,y))

add("hello", "world")

a = ("hello", "world")

b = ("hello", "pthon", "world")

add(a) #错误,a作为一个整体传给了x,报参数错误

add(*a) #正确, 当元组元素的个数于函数参数的个数相同的时候,则x=a[0], y=a[1]

add(*b) #错误, 当元组元素的个数不等于函数参数的个数时,报参数错误

add(y="world", x="hello") #正确,可以指定参数传值,也就是说顺序没有关系

字典作为参数

-------------------------------------

def add(x, y):

print("%s : %s" % (x,y))

d={"y":"world", "x":"hello"}

d1={"y":"world", "x":"hello", "z": "python"}

add(**d) #正确输出==> hello, world

add(**d1) #错误,add() got an unexpected keyword argument 'z'

接受多余参数

------------------------------------------------------

*args(剩余的参数作为元组), **args(剩余的参数作为字典)

$ cat function2.py

def p(x, *args):

print(x)

print(args)

p(1)

p(1,2,3)

==>1

==>()

==>1

==>(2, 3)

p(x=1,y=3)

==> p() got an unexpected keyword argument 'y'

y=3不能作为多余参数保存在args中,可以用**args来保存

-----------------------------------------------------

$ cat function2.py

def p(x,**args):

print(x)

print(args)

p(1)

p(x=2,y=4)

==>1

==>{}

==>2

==>{'y': 4}

p(1,x=3) #错误,第一个参数付给了x,那么相当于穿了x=1,x=3

==>p() got multiple values for argument 'x'

同时接受*args, **args的情况

------------------------------------------------------

def p(x,*args,**other_args):

print(x)

print(args)

print(other_args)

p(1)

==>1

==>()

==>{}

p(3,3,z=5)

==>3

==>(3,)

==>{"z":5}

参数的顺序不能变

p(y=3,3,5) #错误,SyntaxError: non-keyword arg after keyword arg

p(3,4,y=4,5) #错误,SyntaxError: non-keyword arg after keyword arg

lambda表达式

----------------------------------

lambda函数是一种快速定义单行的最小函数, 从lisp借用而来,可以用在任何

需要函数的地方

g = lambda x,y: x+y

g(1,2) ==> 3

lambda的好处:

1.写一些执行脚本,省去函数的定义过程,让代码更简洁

2.省去抽象函数命名的问题

3.让代码更容易理解(sometime)

swtich, python中没有swtich,可以使用字典来实现switch

------------------------------------------------------

x=1

y=4

dd = {

"+": x+y,

"-": x-y

}

print(dd)

print(dd.get("+"))

print(dd.get("-"))

内置函数

----------------------------------------------------

查看文档:

help(str.replace)

str.capilize()

str.split()

str.replace()

异常处理

--------------------------------------------

contents = {"tomato":4, "banana":3}

try:

if contents["apple"] > 3:

print("i have apples")

except (KeyError) as error:

print("i have no %s" % error)

==> i have no 'apple'

评论关闭