代码编写方式:
- 代码编辑器:sublime2。首先创建一个.py文件(使用sublime2编写),然后再Shell中,运行该.py文件。
- Shell。编写一条语句,然后直接执行
基本语法
- 变量名命名规则与c++规则基本一致
- 关键字
- 运算符
- 赋值
多元赋值:y,x=x,y
数据类型
-
- 整型:3(长整型:3L)
- 布尔型:True,False
- 浮点型(float):0.32,9.8e3,-5.3e-2
- 复数型(complex):2.4+5.6j。通过.real,.imag获得复数的实部和虚部,利用.conjugate()获得共轭复数
- 序列类型:
- 字符串(”,’,”’)
- 字符串运算符’u’(Unicode 编码),’r’(原始字符串,让转义字符不起作用):
- f=open('c:\python\test.py','w')#这样写会报错
- f=open(r'c:\python\test.py','w')#这样写,正确
- print u'hello \nworld'
- 元组([])
- 列表(())
- 映射类型:字典
>>>#dictionary
>>>d={'sine':'sin','cosine':'cos','PI':3.14159}
>>>d['sine']
'sin'
函数
查看python内建函数:dir('_buildins_')
使用非内建函数
- import 模块
- from 模块 import 函数
基本语法
if语句:必须缩进
if expression1: code1 elif expression2: code2 else: code3
range(),xrange() 两个函数用法一样,xrange省内存,不过python3中,两者完全一样
range(1,100,2)#步长默认是1 range(5)#默认从0开始,结果是[0 1 2 3 4]
循环
while expression: code
for i in range(1,10,1): code
str='python' for c in str: print c
for i in range(1,10,1): if i>5: break else print i
for i in range(1,10,1): if i<5: continue else: print i
自定义函数
创建
def newfunction(x=1): write code here return y
调用
#传递参数 def getnum(x): return x+x/2 def thefunction(f,y) return f(y) thefunction(getnum,3)
lambda函数
r=lambda x:x+x r(5)
变量作用域
- 内参屏蔽外参
- global语句–全局变量
文件读写
- 打开文件
f=open('filename.txt',mode,buffering='-1')
f.read(size)#size是读取的字节数
- 写文件
f.write('hello world!')
- seek函数
f.seek(offset,whence) #whence: 0表示文件头,1表示当前位置,2表示文件尾
- 标准输入输出 stdin,stdout,stderr
str=raw_input('type in your string:')
print str
网络数据获取
urllib
import urllib r=urllib.urlopen('www.baidu.com') html=r.read()
其中有关正则表达式,资料:
(1) 正则表达式的介绍
http://deerchao.net/tutorials/regex/regex.htm
(2) 正则表达式学习资料:
http://www.java3z.com/cwbwebhome/article/article8/Regex/Java.Regex.Tutorial.html
序列相关操作
- 标准类型运算符
- 值比较
- ’agds’<’kljsd’
- {‘aklsdf’,’asdfas’} is not {‘aklsdf’,’asdfas’}
- 对象身份比较
- 布尔运算
- 值比较
- 序列类型运算符
- 获取
- week[1], week[1:4], week[::-1]
- 重复
- 连接
- 判断
- ’we’ in week
- 获取
- 内建函数
- 序列类型转换工厂函数
- list(‘hello’)
- [‘h’,’e’,’l’,’l’,’o’]
- tupple(“hello”)
- (‘h’,’e’,’l’,’l’,’o’)
- list(‘hello’)
- 序列类型可用内建函数
字符串
- 序列类型转换工厂函数
- 格式运算符
- %d, %8s,
- 转义字符
列表
-.pop(),.pop(0),.append(),.extend(),enumurate()
- 列表解析:动态创建列表,简单灵活有用
- [x**2 for x in range(10)]
元组
元组不可变
- 用处
- 在映射类型中当键值
- 函数的特殊类型参数
- 作为内建参数的返回值
字典
创建
直接创建
aInfo={'Duoge':1991,'Weige':1993,'Jingye':1992}
bInfo=dict([['Duoge',1991],['Weige',1993],['Jingye',1992]])
cInfo=dict(Duoge=1991,Weige=1993,Jingye=1992)
间接创建
dInfo=dict(zip(aList,bList))
参考:
1. coursera课程《用Python玩转数据》,南京大学 张莉,网址:
https://www.coursera.org/learn/hipython/home/welcome