python基础

第1课 安装
    
    软件准备
        python-3.5.1.exe
        pycharm-community-4.5.4.exe

    安装 python-3.5.1.exe
        勾选add python 3.5 to path 选项
        然后选自定义安装
        该页面全部选中,进入到下一页面
        勾选第一个,第五个会自动勾选,下一步安装即可,可调整目录
        看是否安装成功,在cmd中输入python,可以看到版本
        
        python安装完成后,pip也会自动安装完成,
        查看方式 pip --version
        pip相当于手机的应用市场,管理python使用的软件包
        pip就是包管理工具

    
    安装git
        默认是一路下一步,但是有些步骤要知道
        
        勾选如下选项
        windows explorer integration
            simple context menu
                git bash here
                git gui here

        run git from windows command prompt

        checkout windows-style, commit unix-style line endings

    安装完成后
        如果只有一个版本的话,直接在cmd中运行python

        print("aaa") #回车即可
        exit() #退出python

        交互只能运行一行,如果要运行很多行,要创建文件

        创建test.py,用editIDLE来编辑,这是python自带的
        
        print("hello")
        for i in range(2):
            print i
        
        运行 python tp.py,运行是在相应的目录下

        如果有多个版本的话
        py -2 tp.py #以python第二个版本运行
        py -3 tp.py #以python第三个版本运行


第2课 常量和变量
    
    常量:值不能改变
        数字常量:1 100 3.5
        字符串常量:'a' "123"
            '''
            可跨多行
            '''    #3个引号是保留原来3引号字符串中的格式
        布尔值常量:True False
        高级类型常量:[] {}


    变量:值能改变
        通过等号改变它的值,也就是赋值

        a=1
        a=20 #改变了值
        a="hi" #改变了类型
        
        变量的命名:只能包含数字、字母和下划线。
                    数字不能开头
                    区分大小写

                    Aname和aname是不同的变量
                    12name是非法变量名

第3课 数值计算
    
    基础四则
        1+2
        9-7
        23*45
        7/8
        2**3 #表示2的3次方
        在Python3中: 7 / 2 == 3.5 , 即整数除以整数,得到的是浮点数。

    真假判断
        1 > 2
        9 < 7
        23 >= 45
        7 <= 8
        2 == 3
        True != False
    
    逻辑运算
        not 条件
            真假值反转
        条件A and 条件B
            A,B均为真才真
        条件A or 条件B
            A,B一个为真极为真
        
    可通过括号改变运算顺序
    一种简写
        a=a+1 等价于 a+=1
        a=a-1 等价于 a-=1
    
第4讲 列表与For循环
    
    列表:一排
        [1,2,3]
        ["a","b","c"]
        [True, 1, "a"]

    列表取值
        a=[1,"a","3","6","google"] #从0开始
        a[1]是"a"
        a[-1]是"google"
        a[1:4]是["a",3,6] #[) 是前闭后开的区间

    列表添加删除值
        a.insert(0,"fir") #插入第0个元素
        del a[2] #删除第2个元素
        a.append("ch") #插入最后

    列表的遍历
        for item in a:
            print(item)

第5讲 控制流
    
    控制代码的执行顺序

    if语句
        if score>90:
            is_best=True
        elif score>80:
            is_better=True
        else:
            failed=True
    
    break和continue
        row=[1,2,3,4,5]
        for item in row:
            if item == 2:
                continue
            if item == 4:
                break
    
    while 条件
        #do something
        
        例子
        a=[1,2,3,4,5]
        while len(a) > 0: #a还有元素
            if a[-1] == 4:
                continue
            else
                print( a.pop() ) #打印出列表最后一个元素
        
第6讲 函数
    
    函数定义:
        def clean_room():
            clean_table()
            clean_floor()
            clean_trash()
        
    形参:
        def clean_room(room_name):
            clean_table(room_name)
            clean_floor(room_name)
            clean_trash(room_name)
    
        clean_room("主卧")
    
    位置参数:
        def clean_room(room_name, level):
            #clean code

        clean_room("主卧", 2)
    
    关键字参数:
        def clean_room(room_name, level):
            #clean code
        
        clean_room(level=2, room_name="主卧") #明确指明给哪个参数赋值
    
    默认参数:
        def clean_room(room_name, level=2):
            #clean code
        
        clean_room(room_name="主卧") #level默认传2
    
    返回值
        def clean_room(room_name, level=2):
            #clean code
            finished=True
            return finished #如果没有值会返回NULL
        
        success = clean_room(room_name="主卧")
        
    多值返回
        def clean_room(room_name, level=2):
            #clean code
            finished=True
            error_msg = "没有清洁剂了"
            return finished, error_msg
        
        success, msg = clean_room(room_name="主卧") #需要定义两个变量进行接收

    文档字符串
        def clean_room(room_name, level=2):
            '''这个函数用来清理房间          #这是注释,必须放在函数定义的下面,说明功能
            '''
            finished=True
            #clean code
            error_msg = "没有清洁剂了"
            return finished, error_msg
    
第7讲课 模块
    
    模块:以.py结尾的文件称为模块

    包:可包含包和模块,但是其中要包含一个文件, __init__.py
    
    文件夹可包含模块和文件夹,文件夹与包同级,差别在于文件夹没有 __init__.py文件

    例子1:
        test包下文件
            __init__.py  #该文件就是一个空文件
            input.py
                def get_input():
                    print("input")
            parse.py
                from .input import get_input  #同包的调用
                    def do_parse():
                        get_input()
                        print("parse")
        
        tp.py--与test包平级
            from test.parse import do_parse  #不同包的调用
                do_parse()
        
    
    例子2:目录结构如下
        server.py
        models.py
        deps---------tools.py
                |
                -----__init__.py
                |
                -----adapter--------__init__.py
                               |
                               -----xml.py
                               |
                               -----json.py (class JsonAdapter)

    
        server.py中要使用到JsonAdapter, 那么导入的语句应该是:
        from deps.adapter.json import JsonAdapter

    说明:模块被导入时,代码会运行一次,放到缓存中
          再次导入,不会再运行

    小技巧
        1 dir(模块)  -- 查看这个模块,具体的使用需要再学习
        2 模块有一个内置变量 __name__
          一般情况下值为相对引用路径,如"lib.parse"
          在入口模块中值为"__main__"
          if __name__=="__main__"
            #do something
        
第8讲 高级数据类型
    
    元组
        1 与列表很相似,定义为
            (1, "123", 56)
        
        2 不同是,原组是不能改变的,类似于常量
            a=["a", 1, 2]
            a.append(3)
            但是原组是不能增加或删除元素的
        
        3 (2)其实是2,(2,)就是原组
        
    字典
        字典定义为
        {
            "123":123,
            456:"hello"
        }
        是一种映射的关系

        a={"123":123,456:"hello"}
        a["123"] #字典取值,得123
        a[456]="world" #字典设置值

    字符串
        字符串其实是一个特殊的列表,列表中每个元素是一个字符

        a="hello lilei"
        a[:5] #"hello",这是字符串切片 字符串本质是常量,可以查询,不能修改
        a="hello %s" % "lilei" #占位符替换
        a="%s %s" % {"hello", "lilei"}
        a="%{verb}s %{name}s" % {"verb":"hello", "name":"lilei"} #字符串中替换变量的使用

    有关函数
        当一个函数返回多个值的时候,它实际上返回了一个原组,如 a,b=fun()
        a,b=(1,2)
        
        #元组传参
        param=(1,2)
        add(* param)
        与
        add(1,2)一样
        
        #字典传参
        param={"a":1,"b":2}
        param(**param) -->  param(a=1, b=2)
    

第9课 类和对象
    
    定义一个猫类
        class Cat:
            leg_cnt = 4 #类属性
            def __init__(self, cat_name):
                self.name=cat_name
            def change_name(self, cat_name):
                self.name=cat_name
            def climb(self):
                print("cat %s climb a tree" %self.name)
    
    使用Cat这个类
        tom = Cat("Tom") #self由python自动传递
        tom.change_name("ATom")
        tom.climb()
        tom.leg_cnt == 4 #访问类属性

    类的继承
        class PersianCat(Cat):
            def __init__(self, cat_name):
                super().__init__(cat_name)
            def jump(self):
                print("try jump")
        
        jack = PersianCat("jack")
        jack.jump()
        jack.climb()


第10课 文件处理
    
    写入文件
        poem='''\
        Programming is fun
        When the Work is done
        if you wanna work also fun:
            use Python!
        '''

        # '''\ 这个斜线表示让结尾的换行符失效。
        # '''表示按文本自身的格式

        f=open('poem.txt', 'w') #w(重新写入) r a(追加) 该文件写入当前文件夹
        f.write(poem) #write text to file
        f.close()

    读取文件
        f=open('poem.txt') #默认是r
        while True:
            line = f.readline()
            if len(line) == 0:
                break
            print(line, end="")
            #print内容后面默认会增加一个\n
            #这里end禁止结尾加\n,改为加""
        f.close()

    读写文件的简便方式
        #write
        with open('poem.txt', 'w') as f:
            f.write(poem)

        #read
        with open('poem.txt') as f:
            while True:
                line = f.readline()
                if len(line) == 0:
                    break
                print(line, end="")

        #说明:离开with语句会自动关闭文件


第11课 异常处理
    
    Exception--AssertError ValueError--异常对象
    
    格式
    try:
        一段可能出错的代码
    except ValueError as e:
        print(e) #处理这个异常
    except Exception:
        处理其余所有的异常
    else:
        没有异常的处理代码

    
    说明:try下面的三段代码只有一段会执行

    格式:
    try:
        一段可能出错的代码
    finally:
        最后一定会执行的代码,例如
        f.close()
    
    格式:抛出异常
    raise e

    例子:
    try:
        int("a")
    except ValueError as e:
        print(e) #打印异常
        raise e #加上这句让是抛出异常,让外面来处理


====补充课程====

第一课 装饰器

    具体内容参见ppt

    

        

    
    1 函数可作为参数进行传递,函数就是变量,类型为函数
        def make_list(a, b)
            return [a,b]

        def add(a, b)
            return a+b

        def play_with_number(do_func, a, b)
            return do_func(a, b)

        print(play_with_number(add, 2, 1))
        print(play_with_number(make_list, 2, 1))

    2 函数可以作为返回值返回
        import random

        def random_action(): #函数里面定义两个函数
            def make_list(a, b):
                return [a, b]

            def add(a, b):
                return a+b

            actions = [make_list, add]
            return random.choice(actions) #随机返回一个函数

        action=random_action()
        print(action(2,1))

    3 函数可以使用外层空间的变量,图片中画星星的变量都可以使用
        import random

        def random_action(n): #注意n的使用
            def make_list(a, b):
                return [a, b] * n

            def add(a, b):
                return (a+b) * n

            actions = [make_list, add]
            return random.choice(actions)

        action=random_action(3)
        print(action(2,1))    

    4 根据上面3点性质,以函数为参数,并返回一个函数
      输入函数A ---- 函数(增强) ---- 输出函数B
      这个 函数(增强) 就是装饰器

    5 装饰器的使用--打印函数的调用参数
        增强函数的使用@符号
        
        原始
            DEBUG = True

            def print_args(funcA):
                def funcB(a, b):
                    if DEBUG:
                        print(a, b)
                    return funcA(a, b)
                return funcB

            def make_list(a, b):
                return [a, b]

            action = print_args(make_list)
            action(1,2)
        
        装饰
            DEBUG = True

            def print_args(funcA):
                def funcB(a, b):
                    if DEBUG:
                        print(a, b)
                    return funcA(a, b) #调用函数A
                return funcB

            @print_args  #我的理解 make_list 作为参数传给 print_args,表示该函数增强了
            def make_list(a, b):
                return [a, b]

            make_list(1,2) #这是增强了的 make_list 的函数
        
        原始与装饰的逻辑一样,只是写法不一样
        
    6 适配参数
        
            
    7 位置参数与关键字参数 1
        函数定义
            def function_name(a,b,c,d,g,e,f="a"):
                pass
            def function_name(*args, **kwargs): #第一个参数是位置参数,第二个参数是关键字参数
                pass
                #args是原组(1,3,4,6) kwargs是字典{"e":2,"f":"a","g":True}
        函数调用:
            function_name(1,3,4,6,e=2,f="a",g=True)
            #调用时 有=号的写到没有=号的后面
            #普通参数不能乱序,关键字参数可以乱序
        
    8 位置参数与关键字参数 2
        传入不确定个数个参数
        function_name(1,3,4,6,e=2,f="a",g=True)
        
        pos_args=(1,3,4,6)
        name_args={"e":2,"f":"a","g":True}
        function_name(*pos_args, **name_args)
        
    9 可接收任何可能的参数
        DEBUG = True

        def print_args(funcA):
            def funcB(*pos_args, **name_args):
                if DEBUG:
                    print(pos_args, name_args)
                return funcA(*pos_args, **name_args)
            return funcB

        @print_args
        def make_list(a, b):
            return [a, b]

        @print_args
        def add(a, b, c=3):
            return a + b + c

        make_list(1,2)
        add(1,2,3)
        
        

第二课 删除文件中的空行和空白

    "  123  ".strip() #"123"
    " \r 123567  \n ".strip() #"123567"
    "  \r 123 567 \n".strip() #"123 567"

    strip()是生成新的字符串

    "123abc32".strip("123") #字符串两遍过滤123,结果为"abc"
    
    去空行代码 vim trans.py
    with open("more", "r") as f:
        for line in f.readlines():
            line = line.strip()
            if len(line) > 0:
                print(line)
    执行
    python3 trans.py

    输到另外文件中
    python trans.py > less
    vim less #less这个文件有内容

    乱码问题
    result = []
    with open("more", "r") as f:
        for line in f.readlines():
            line = line.strip() #加上.decode("utf-8") 这句也是乱码
            if len(line) > 0:
                result.append(line)
    print(result) #打印出来的结果为乱码,这就需要看编码问题
        
第三课 内置变量
    
    print "a.py"+__name__ #输出为a.py__main__
    
    在b.py中
    print "b.py"+__name__

    在a.py中
    import b
    print "a.py"+__name__

    运行a的结果为
    b.py:b #模块名,在引入的时候就执行了
    a.py:__main__

    在b.py中调整
    if __name__ == "__mian__"
        print "b.py"+__name__


第四课 类方法和静态方法
    
    结合ppt看

    例子1:类方法
        class Cat():
            total_count=0 #类属性
            
            def __init__(self, name):
                self.name=name
                self.born_one()

            def say_hello(self):
                print("I'm %s, hello" % self.name)

            @classmethod
            def born_one(cls): #类方法
                cls.total_count += 1

        tom = Cat("tom")
        lily = Cat("lily")

        tom.say_hello()
        lily.say_hello()

        print(Cat.total_count) #打印结果为2

    例子2:静态方法
        class Cat():
            total_count=0
            def __init__(self, name):
                self.name=name

            def say_hello(self):
                print("I'm %s, hello" % self.name)

            @staticmethod
            def get_leg_count(): #静态方法
                return 4

        print(Cat.get_leg_count())


    对象有的类没有,类有的对象也有
    静态方法就是类方法
        
    
第五课 查看软件包信息
    
    在windows下无法查看目前,是不是需要安装所需的开发包??

    #查看源代码
    import django
    django.__file__
    cd 进入 查看源代码

    #查看版本
    import django
    django.VERSION
    MYSQLdb.__version__
    
    #查看django都有哪些属性,便于查看
    dir(django)

第六课 with的使用
    
    结合ppt看
    
例子1:简单应用,无异常情况
    
    class UserFile():
        
        def __init__(self, path, mode): #构造函数
            self.path = path
            self.mode = mode
        
        def __enter__(self): #返回对象
            return self

        def write(self, text): #实际定义的函数
            print(text) #简单输出
        
        def __exit__(self, exc_type, exc_value, exc_tb): #是否有异常
            pass
    
    with UserFile('/tmp/a.txt', 'w') as f:
        f.write("hello world") #打印出 hello world
        

例子2:简单应用,有异常情况,注意代码中最好不要有中文

    class UserFile():
        
        def __init__(self, path, mode):
            self.path = path
            self.mode = mode
        
        def __enter__(self):
            return self

        def write(self, text):
            print(text)
        
        def __exit__(self, exc_type, exc_value, exc_tb):
            print(exc_type)
            print(exc_value)
            print(exc_tb)
            return True #True表示不会抛出异常,
                        #False 或 什么都不写,表示抛出异常让python来处理
    
    with UserFile('/tmp/a.txt', 'w') as f:
        f.write("hello world")
        int("hello") #将值转化成整数,如果不能转则抛出异常
    
    #接抛出的异常
    try:
        with UserFile('/tmp/a.txt', 'w') as f:
            f.write("hello world")
            int("hello") #将值转化成整数,如果不能转则抛出异常
    except ValueError:
        print("我捕获到了异常") #这里接到抛出的异常,不会继续向上抛出



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值