python_intro

Python入门

谭 泽 超

内容介绍Python初级

变量,表达式,控制结构,函数等

复杂数据类型及I/O

string,list'[]',tuple'()', dict '{}'

高级数据结构

类,链表,队列,树等

代码实例

Python初级Python简介

变量与表达式

条件语句与循环

函数

Python简介

面向对象的解释语言

优点

可读性好,容易上手

丰富的库,正则表达式、线程、数据库、FTP、电子邮

件、XML、HTML、GUI等

扩展,移植

参考资料

参考手册

Python使用方式命令行方式

$python

脚本方式

$ python hello.py

$ ./hello.py

例子

变量

直接使用,不需要先声明

以'_'或字母开头,不能有关键字和非法字符

a = 1, a = 1.1, a = "Hello World"

type

表达式

语法与C语言类似

赋值:=

算数运算符:+, - ,* , /, %,**

"abc" + "def", "abc"*3

条件语句

布尔表达式:==, <, >, <=, >=, !=

逻辑操作符:and, or, not

if x > 0 and True or not False:

.......#操作

elif ...:

else:

......

for 循环,用于访问元素

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

.......#do some thing

for line in fp.readlines():

print line;

for i in "Hello World!":

print i,

x = 0

While x < 10:

print x

x += 1

函数(一)

type, id

int(2.1), float(”3.2”), str(3.2)

Math 函数

import math

math.log(), math.sin(), math.pi, math.sqrt()

函数(二)

def reverse(s):

if(not isinstance(s,str)):

print "Bad parameter! String Only!\n"

return -1

for i in range(len(s) - 1, -1, -1):

print s[i],

复杂的数据类型字符串string: "hello World"

列表list: [1, 2, 3]

元组tuple:(1, 2)

字典dict: {1:2, 2:3}

字符串

x="hello world"

x[0], x[1], x[-1]

len(x): 字符串长度,11

分片:y=x[1:], y=x[:4], y=x[1:6], y=x[:]

字符串(二)import string

查找,str.find(sub[, start[, end]])

分割,str.partition( sep)

划分,str.split([sep [,maxsplit]])

替换,str.replace(old, new[, count])

列表

a=["hello", 2.0, 5, [10, 20]]

a[0] = 3

del a[1]

分片,y = a[1:5]

复制,z = a[:]。x = z, 不是复制,是别名

a.append(6)

元组操作与列表基本一致

不可修改内部元素

x, y = y, x

字典

d = {}

d[0] = 1, d['x'] = 56, d[1,2] = 3

列表,字典不能做为关键字

d[2] = d.get(2, 0) + 1

d.keys(): [0, 'x', 2, (1,2)]

d.has_key(k): Ture, False

d.values(): [1, 1, 3, 56]

d.items(): [0:1, 'x':56, (1,2):3, 2:1]

标准I/O

标准输出:print "format" % (...),

标准输入:

x = raw_input([promt])

x = input([promt])

命令行参数import sys

sys.argv: []

sys.argv[0]: 程序名

相关主题
相关文档
最新文档