Python笔记

来源:互联网 发布:芝麻分开通阿里云主机 编辑:程序博客网 时间:2024/05/21 11:30

    Python,由吉多·范罗苏姆(Guido van Rossum)在1989打发圣诞节放假时间的一门“课余”编程项目,至今已有二十多年的历史,语法简洁清晰,深受喜爱;

  1. 小窥
    # 查看版本python -V  # 输出print "hello" # 输入str = raw_input("press any key")print str# 注释print "www.cnblogs.com" # link  # 帮助dir(list)help(list)
  2. 变量
    # 无需声明和删除,直接赋值;type为内置函数,查询类型;a = 10print a,type(a)a = “hello”print a,type(a)a += “ word”print a,type(a)
  3. 列表、元组和词典
    ###### 1. 列表:list,数据如同STL <list>,下标从0开始,支持添加删除province = ['GuangDong', 'ZheJiang', 'HeNan', 'XinJang', 'HeiLongJiang']print province[2]province.append(‘HuBei’)delete province[1]# 访问支持:[下限:上限:步长],上限不包括在内print province[:3]        # idx from 0 to 7print province[3:]          # idx from 3 to endprint province[0:5:2]     # from 0 to 4 with 2 stepsprint province[3:0:-1]    # from 2 to 1 with -1 stepsprint province[-1]          # the last oneprint province[-3]          # the second one from last                    ###### 2. 元组:Tuples,如同list,不过不能改变;如12个月英文名之类的常量days = ('Morning','Afternoon','Night')print days,type(days)# 字符串是一种triplestr = “Hello world”print str[2:5]###### 3. 词典:Dictionaries, 如同hash, 元素结构为 key:value;如成绩stu_score = {'ZhangSan':34,'LiSi':98, 'WangWu':99}# 新增key:valuestr_score['LiLei'] = 100# 删除keydelete str_score['ZhangSan']# 检查    if str_score.has_key(‘HanMeiMei’):    print “got HanMeimei else     print “not find HanMeiMei# 打印所有key,values print stu_score.keys(),str_score.values()values = stu_score.values()values.sort()print values,length(values)
  4. 循环
    # Python中语句后无“;”结尾;无“{}”,通过TAB(4个空格)# 1. whilea = 0while (a < 10)        a += a+1;        print a# 2. ify = Trueif y == True:        print “y is true”elif y == False:        print “y is false”else:        print “value of y is error.”#3. Fortmp = [1,’a’,’sdfa’,242]for value in tmp        print value# 判断符号 >, >=, <, <=, ==, !=, in
  5. 函数
    # 定义函数showdef show(list, info)        for entry in list:            print entry        return input(info) + 1    # input输出数字# 表传指针,bulid-in传值list = [1,2,3]info = “press num: “def show (list, info)        list[1]=3        info = “changed”show(list, info)print list,info

  6. # 定义类class Shape        def __int__(self, x, y): # 构造            self.x = x            self.y = y        def area():            print self.x * self.yshape = Shape(100,20)class Square(Shape)    # 继承        def __int__(self, x):            self.x = self.y = x# 对象词典class_dic = {}     class_dic[“Shape”] = Shape(100,20)class_dic[“Square”] = Square(100,20)print class_dic[“Shape”].areaprint class_dic[“Square”].area
  7. 模块
    # 模块:只定义集(库),比如变量、函数和类# 可以自定义模块和模块包import test_moduleimport dir.module  # 相同类型放一个目录
  8. 文件操作
    Ofile = open(‘file’, ‘r’)Ofile.seek(45,0)# 支持seek、tell, readline, readlins, wirte, close
  9. 异常处理
try:    a = input(“press characters”)except NameError:    print “input a num”

 

[Reference]

http://zh.wikipedia.org/zh-cn/Pythonhttp://www.sthurlow.com/python/http://www.cnblogs.com/vamei/archive/2012/05/28/2521650.html
原创粉丝点击