PYTHON笔记
# 注释
\ 下行继续
; 逻辑换行
1.
If (条件) : (语句) elif(条件) : (语句)else: (语句)
PS: PTTHON是靠缩进来判断层次的,所以缩进很重要
2.
For:…in…else:
For i in range(1,5)
Else:
3.
While (条件) : (语句)
4.
函数:
Def
Return…..
5.
函数里定义 global X 变量,函数外可以改变他的值
6.
可以以 def test(a,b=1,c=2) 形式设置默认值
调用 test(3)
7.
Import sys
8.
创建自己的模块:
#!/usr/bin/python
# Filename:
mymodule
.py
Def sayhi():
‘hi’
Version =’0.1’
把上面语句保存成mymodule
.py
放到sys.path或者运行程序所在的目录下
调用方法:
Import mymodule
Mymodule.sayhi()
9.
从某个基本模块导入函数:
From mymodule import sayhi;
Sayhi();
10.
数组
定义:listA=[‘a’, ‘b’, ‘c’, ‘d’]
数组长:len(listA)
添加:listA.append(‘e’)
排序:listA.sort()
调用一个元素: listA[0]
删除:del list[0]
调用区间:list[1:3] 从第一个到第三个
11.
元组
定义:zoo=(‘a’,’b’,’c’)
长度:len(zoo)
二维:new_zoo=(‘a’,’b’,(‘c’,’d’)) 调用: new_zoo[2][1]
12.
字典
定义:
添加: ab[‘D’]=’4’
删除: del ab[‘c’]
全调用:
For A,B in ab.items()
13.
引用和复制
引用: listA=[‘a’,’b’]
复制:listA=[‘a’,’b’]
14.
字符串处理
strA=’swaroop’
if name.startswith(‘swar’): 以…开始
if ‘a’ in name: 是否存在‘a’
if name.find(‘war’)!=-1 查找
用字符串把strA数组连接起来:
strA=’-@-’
ð
替换:
strA.replace(‘a’,’b’)+’zip’
15.
文件读写
写文件:
F=file(‘1.txt’,’w’)
f.write(‘abc’)
f.close
读文件:
F=file(‘1.txt’)
16.
异常处理
Try:
…
Except eoferror:
Except:
Finally:
17.
os方法处理
os.getcwd()
os.listdir() 返回指定目录下所有文件和目录
os.remove()
os.path.isfile() os.path.isdir() os.path.existe() 判断是否是文件,目录,文件是否存在。
求数组中的最小值:
>>>counts=[809,432,5436,24342,3125,654,324,231]
>>>low=min(counts)
>>>min_index=counts.index(low)
>>>print min_index
简洁版:
>>>counts=[809,432,5436,24342,3125,654,324,231]
>>>counts.index(min(counts))