day1-4

1    向别人介绍自己
2     幽默,别紧张
3     版本:2.4-->3.0-->2.6-->2.75-->3.4
4     先入为主,够用就好
5     pythonxy ,portable python(绿色版)
6     Python -v
7     linux: #!/usr/bin/env python
8     python解释器:
        Cpython 
        Ipython(皮肤) 
        Jython(与java结合) 
        PYPY(速度快) 
        IronPython(与c#结合) --.net version
9     编程风格:
        1、缩进统一 
        2、变量
            第一个字符:A-Za-z_
            其他字符:A-Za-z_0-9
            大小写敏感
            尽量名词
10     indent 缩进
11     def main():
        print 'hello'
    main()
12     常量使用大写
13    a=2,b=a,a=5 ==> a=? b=?  ==>id (a) 代表a指向的内存地址,也就是5的内存地址。
14     True /False
15     a**32 ==>long
    a**12 ==>int
16    /  vs //
17    你们要是不反应,我以为我说错了呢。
18    '''多行注释,格式化输出  '''   
19    字符编码 ASCIIC(一个字节)  ==> Unicode(两个字节) ==> UTF-8 (变长) 
            ord('A')=65                                    英文1字节
            ord('a')=97                                    中文3~4字节
20    name=u'范特西'
    name
    print name
    len(name)  =>3   ???
    name_utf8=name.encode('utf-8')  ==>转换为utf8
    len(name_utf8) =>9
    print '\xe8\x8c\x83'
    name.decode('utf-8')   ==>转换为unicode
21    os.system('pwd')
    os.popen('pwd').read()
    commands.getstatusoutput('pwd')
    import os
    import commands
    import tab
    os.walk('/tmp')
    import sys
    print sys.argv
    print sys.argv[2]
    from sys import argv
    import multiprocessing as multi
    from sys import *
22    name=raw_input('Please input your name:')
    age = int(raw_input('age:'))
    age = input('age:')    ==>原生格式是什么就是什么,15 'alex' alex
    print '''
    Personal informatrion of %s:
        name:%s
        Age :%d
        job :%s
      Salary:%f 
    ''' % (name,name,age,job,salary)
    help(input)
23    if age > 40 :
        msg = 'you are too old!'
    elif age > 30 :
        msg = 'you are little old!'
    else :
        msg = 'you are young'


24    for i in range(10):
        i ==> 0..9 
    print '\033[32;1mGOOD! 10 RMB!\033[0m' 
25    count=0
    while count < 10000:
        count += 1
    else: 
        print count 
26    linux:tab   vs  windows:tab 
    tab键            4个空格
27    lock_check = file(lock_file)
    for line in lock_check.readlines():
        line = line.split()
        if username == line[0]:
            sys.exit('user %s is locked !' % username)
    f = file(account_file,'rb') 
    for line in f.readlines(): 
        user,passwd = line.strip('\n').split()
28    一模一样的代码尽量只出现一次。
29    工欲善其事,必先利其器。
30    f=file('myFile.txt','r')
    for line in f.readlines():
        line = line.strip('\n').split(':')
                    脱掉(默认不可见字符)
        print line
    f.close()    
    f.flush()
31    r:只读(默认)
    w:只写(若文件存在会覆盖,若文件不存在会新建)
    a:追加
    r+b:读写
    w+b:写读
    a+b:追加和读模式
32    字符串处理
    s.find('alex')  返回字符串中alex的位置,找不到返回-1
    s.rfind  反向查找
    s.index  与find相同,不过找不到的话会报错而不是返回-1
    s.rindex  反向查找
    s.count  反馈找到几个字符串
    s.capitalize 首字母大写
    s.lower 小写
    s.upper 大写
    s.swapcase 大小写互换
    s.split 分割,默认按照空格
    '|'.join(msg_list)  将列表转换为字符串  vs  +=
    len()  字节
    cmp 比较字符的大小
    ord('A')=65
    max() 返回字符串中最大的字符
    min() 返回字符串中最小的字符
    startwith() 是否以xx开头
    endwith() 是否以xx结尾
33    import sys
    sys.path
    /usr/lib/python2.7/dist-packages
34    列表
    name_list.append('Eric')
    name_list.insert(2,'100')
    name_list.remove('old gou')
    name_list.count('jack')
    name_list.index('jack',0)
    del name_list[2]
    name_list.reverse()
    name_list.sort() 按照ASCII码排序
    name_list.extend('abcd')   'a','b','c','d'
    name_list.extend(info)   vs  name_list += info  其中info是另一个列表
    name_list[2:5]   顾头不顾尾  name_list[-5:-1]  name_list[0:5]  name_list[:5]  name_list[-5:]
    name_list[name_list.index(2):name_list.index(2)+4]
    name[1::2]
35    元祖(常量数组)
    count()
    index()
    a=tuple(a)
    a=list(a)
36     字典,所有的key必须的唯一的
    name_info = {
        'name':'Jacky',
        'age':29,
        'job':'Engineer'
    }
    name_info['salary']=3000
    name_info['job']='IT'
    name_info.pop('job')
    for i in name_info:
        print i    #打印key
    for i in name_info:  #效率高
        print i,name_info[i]
    for k,v in name_info.items():  #效率低
        print k,v
    d.get(key,0)  #找不到不会报错,而是返回0,默认null   vs   d[key]
    d.has_key(key)
    d.keys()
    d.values()
    d.popitem() #随机删除一个
    d.setdefault('stuID',1123)  #如果没有stuID则生产,如果有则不改变
    d.update() #merge  合并,若没有key则加,若有则改
    d.copy()  #浅复制 ,只复制一层
    import copy 
    d1=copy.deepcopy(d) #深复制,耗内存
    d2=d   #别名
37    dict:
        插入和查找速度很快,不会随着key的增加而增加
        需要占用大量内存,内存浪费多(做了hash)
        key不可变
        默认无序
    list:
        查找和插入的时间随着元素的增加而增加
        占用空间小,浪费内存很少
        通过下标查询
        有序
38     集合set
    特点:无序,元素不重复
    功能:关系测试,去重
39    name_set={1,2,4,5}
    set({1,2,4,5})
    name_set.add(1)  #如果有1则不变,如果无1则添加1
    a.pop()
    x={1,2,3,4}
    y={3,4,5,6}
    x & y   #set({3,4})
    x | y    #set({1,2,3,4,5,6})
    x - y   #set({1,2,})
    x ^ y     #set({1,2,5,6})  对称差集
    a.issubset(b) #a是b的子集
    a.issuperset(b) #a是b的超集
40    作业1:
        员工信息表:xingming  dianhua gongsi youjian
        用户可以模糊查询员工信息
        高亮显示匹配的信息,显示匹配了多少条
    作业2: 
        购物车程序:
        要求用户输入工资,然后打印购物菜单
        用户可以不断的购买商品,直到钱不够为止
        退出时格式化打印用户已购买的商品和剩余金额
41    模块和模块的常用方法
    __init__.py
    if __name__ = '__main__'
    __file__
    __doc__  #模块注释  vs   函数注释
    http://www.cnblogs.com/wupeiqi/articles/4276448.html
42    def fun(args,*args,**args)
            变量,列表,字典
43    yield:
    def AlexReadlines(): 
    seek = 0 
    while True: 
        with open('D:/temp.txt','r') as f: 
            f.seek(seek) 
            data = f.readline() 
            if data: 
                seek = f.tell() 
                yield data 
            else: 
                return 
    for item in AlexReadlines(): 
    print item
44    三元运算:
    result?=?'gt'?if?1>3?else?'lt‘
45     lambda表达式:
    a?=?lambda?x,y:x+y
    print?a(4,10)
46    randon模块
    print?random.random() #0~1的随机数
    print?random.randint(1,2) #[1-2]的随机整数
    print?random.randrange(1,10) #[1-10)的随机整数
47    md5加密
    import?hashlib
    hash?=?hashlib.md5()
    hash.update('admin')
    print?hash.hexdigest()
48    json:
    import json
    data = {'k1':123,'k2':'hello'}
    j_str = json.dumps(data)
    print j_str
    with open('F:\python_src\Day3_hw\json.txt','w') as fp:
        json.dump(data,fp)
    print json.loads(j_str)
49     正则表达式re模块
    compile,match,search,findall,group,groups
    字符:\d \w \t
    次数:* + ? {m} {m,n}
50    时间模块:
    时间的三种表达方式:
        1、时间戳
        2、元祖
        3、格式化字符串
    import time
    print time.mktime(time.localtime())       #1523118242.0
    print time.gmtime()#可加时间戳参数 time.struct_time(tm_year=2018, tm_mon=4, tm_mday=7, tm_hour=16, tm_min=24, tm_sec=2, tm_wday=5, tm_yday=97, tm_isdst=0)
    print time.localtime() #可加时间戳参数 time.struct_time(tm_year=2018, tm_mon=4, tm_mday=8, tm_hour=0, tm_min=24, tm_sec=2, tm_wday=6, tm_yday=98, tm_isdst=0)
    print time.strptime('2014-11-11','%Y-%m-%d') #time.struct_time(tm_year=2014, tm_mon=11, tm_mday=11, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=315, tm_isdst=-1)
    print time.strftime('%Y-%m-%d')#默认当前时间2018-04-08
    print time.strftime('%Y-%m-%d',time.localtime())#默认当前时间2018-04-08
    print time.asctime() #Sun Apr 08 00:24:02 2018
    print time.asctime(time.localtime()) #Sun Apr 08 00:24:02 2018
    print time.ctime(time.time()) #Sun Apr 08 00:24:02 2018
51    面向对象:
    多态、继承、封装
52    放射:
    data = raw_input("please input address:")
    array = data.split('/')
    userpance = __import__('backend.'+array[0])
    model = getattr(userpance, array[0])
    func = getattr(model, array[1])
    func()
53    装饰器:
    def outer(f):
        def aaaa():
            print "aaa"
            f()
            print "bbb"
        def bbbb(aa):
            print "ccc"
            result = f(aa)
            print "ddd"
            return result
        return bbbb
    @outer
    def Func1(aaa):
        print "Func1"  
        print aaa
        return 'return'
    response = Func1('xxxxxxx')
    print response
54    面向对象编程:
    class Province:
        memo = '中国的23个省之一' #静态字段
        
        #构造函数
        def __init__(self,name,capital,leader):
            self.Name = name #动态字段
            self.Capital = capital 
            self.Leader = leader 
        
        #动态方法
        def sports_meet(self):
            print self.Name + '正在开运动会'
            
        #静态方法
        @staticmethod
        def Foo():
            print '每个省要带头防腐'
        
        #特性
        @property
        def Bar(self):
            print self.Name 
            
        #析构函数
        def __del__(self):
            print '销毁对象时调用'
        
        #调用方法Province()
        def __call__(self):
            print self.Name
    hb = Province('河北','石家庄','李阳')
    sd = Province('山东','济南','王胜辉')
    print hb.Capital
    print Province.memo
    #类不能访问动态字段
    #print Province.Name
    #对象可以访问静态字段
    print hb.memo
    #动态方法
    hb.sports_meet()
    sd.sports_meet()
    #静态方法
    Province.Foo()
    #执行特性
    hb.Bar
55    异常处理
    try:
        xxxxxx
    except ImportError,e:
        print 'xxx'
    except AttributeError,e:
        print 'yyyy'
    except (ImportError,AttributeError),e:
        print 'zzzz'
    except Exception,e:
        print 'asdf'
    else:
        print "没有出错"
    finally:
        print "无论是否有异常都处理"
56    自定义异常:
    class MyException(Exception):
        def __init__(self,msg):
            self.error = msg 
        def __str__(self,*args,**kwargs):
            return self.error 
    obj = MyException('错误')
    print obj  #会输出__str__的值
    raise MyException('自定义错误') #手动触发错误
57    抽象类(接口)
    from abc import ABCMeta, abstractmethod
    class Bar:
        __metaclass__ = ABCMeta
        @abstractmethod
        def Fun(self):
            pass
    class Foo(Bar):
        def __init__(self):
        print '__init__'
    Foo()

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/31441616/viewspace-2152782/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/31441616/viewspace-2152782/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值