• Python学习(一)基础语法


    1. 入门

    1.1 解释器的作用

    Python解释器作用:运行文件。
    Python解释器类型:

    • CPython:官方开发的C语言解释器
    • IPython:基于CPython的一种交互式解释器
    • PyPy:基于Python开发的解释器
    • Jytion:运行在Java平台的解释器,直接把Python代码解析为Java字节码执行
    • IronPython:运行在.Net平台的解释器,将Python代码编译为.Net字节码

    1.2 下载

    官网:https://www.python.org/
    注意Add Path。
    验证:打开cmd,运行python.

    (venv) F:\myStudySpace\pythonStudy\spider\web_crawler>python
    Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    
    • 1
    • 2
    • 3
    • 4

    1.3 基础语法

    输入输出语法与引号

    print()
    print('')
    print('''多行''')
    print("")
    print("""多行输出""")
    print(123)
    inputTxt = input("plese input:")
    print(inputTxt)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    注释:

    # 单行注释
    """
    多行注释
    """
    '''
    多行注释
    '''
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    变量:

    变量是一个存储数据的时候,当前数据所在内存地址的名字。
    变量名 = 值
    变量名规则:字母、下划线和数字组成。不能以数字开头

    数据类型与四则运算

    数据类型

    • 字符串,拼接用+号
      print('hello')
    • 整型
      print(99)
    • 浮点型
      print(3.14)
    • list列表:[]
      • 下标从0开始
      • 切片语法:[起始:结束:步长]。左闭右开区间取值
    name = "abcdef"
    print(name[0])
    # 取到结束
    print(name[:])
    # 取到结束
    print(name[0:])
    # 取到结束前一个
    print(name[0:len(name)-1])
    print(name[:len(name)-1])
    print(name[:len(name):2])
    """
    a
    abcdef
    abcdef
    abcde
    abcde
    ace
    """
    list_2 = ['a','b','c','d','e','f']
    print(list_2[5])
    print(list_2[0:len(list_2)-2:2])
    ## 反转
    print(list_2.reverse())
    del list_2[2]
    print(list_2)
    # 删除列表最后一个元素
    list_2.pop()
    print(list_2)
    # 增加元素
    list_2.append("6666")
    print(list_2)
    """
    f
    ['a', 'c']
    None
    ['f', 'e', 'c', 'b', 'a']
    ['f', 'e', 'c', 'b']
    ['f', 'e', 'c', 'b', '6666']
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • dic字典(对应map):{}
    xixi = {'name':'xixi',"age":18,'height':166.6}
    print("正常的字典值:",xixi)
    print(xixi['name'])
    print(xixi.get('name'))
    xixi["addr"] = "浙江"
    print("增加后",xixi)
    xixi["addr"] = "上海"
    print("修改后",xixi)
    del xixi["addr"]
    print("删除后",xixi)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    四则运算

    加、减、乘*、除/、取模%、幂**

    数据类型的查看type()

    ## 数据类型
    str_1 = "123"
    print(type(str_1))
    str_2 = 123
    print(type(str_2))
    str_3 = 123.123
    print(type(str_3))
    list_1 = [1,2,3]
    print(type(list_1))
    # json
    json_1 = {"name":"Huathy","age":18}
    print(type(json_1))
    # 
    # 
    # 
    # 
    # 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    数据类型的转换int()int()float()

    在这里插入图片描述

    流程控制

    • 单项判断:if
    • 双向判断:if…else…
    • 多向判断:if…elif…else…
    • if嵌套
    # 单项判断:if
    a = 0
    if a==0:
        print('1')
    # 双向判断:if...else...
    if a==0:
        print('1')
    else: print(2)
    # 多向判断:if...elif...else...
    if a==1:
        print('1')
    elif a == 0:
        print(2)
    else:
        print(3)
    # if嵌套
    score = 60
    if score >= 60:
        print("及格")
        if(score>=80):print("优秀")
        else:print("还需努力")
    else:
        print("不及格")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    格式化输出

    name = 'xixi'
    age = 18
    height = 166.6
    print("name is: %s,age is %d ,height: %1f" % (name, age, height))
    print("name is: {},age is {} ,height: {}".format(name, age, height))
    
    • 1
    • 2
    • 3
    • 4
    • 5

    循环与遍历

    逻辑运算符

    • and:a and b。类比Java的&&
    • or:a or y。类比Java的||
    • not:not x。类比Java的!

    list遍历

    # range()函数 默认从0开始
    for i in range(5):
        print(i)
    #
    print("===================")
    # range 指定从一开始(左闭右开)
    for i in range(1,5):
        print(i)
    
    list_1 = ['xiix1','xi2','xi3','xi4']
    # for in
    for name in list_1:
        print(name)
    print("while =============")
    # while
    i=0
    while i < len(list_1):
        print(list_1[i])
        i += 1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    字典dict遍历

    dict_name = {'name':'xixi','age':18,'height':166.6}
    for key in dict_name: print('key',key)
    print("=================================")
    for val in dict_name.values():print('val',val)
    print("=================================")
    for key,val in dict_name.items():print(key,'--',val)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    跳出循环

    • break
    • continue
    print('break')
    name = 'python'
    for x in name:
        if(x == 'h'):break;
        print(x)
    print('continue')
    for x in name:
        if (x == 'h'): continue;
        print(x)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    面向对象OOP(封装、继承、多态)

    封装:函数、全局变量与局部变量

    """
    函数代码块以def开头,接标识符名称和(形参)
    """
    def add(x,y):
        print(x,y)
        return x+y
    
    print(add(1,2))
    def none_fun():return
    print(none_fun())
    
    # 全局变量
    a = 10
    def inner():
        # 内部变量
        b = 20
        print(a)
        print(b)
    inner()
    # gloabl 修饰词:使用global对变量进行修饰,告诉计算机该变量变成全局变量在任何地方都起作用。类似js的var
    
    def func():
        global a
        print('func a1', a)
        a = 200
        print('func a2',a)
    func()
    
    print(a)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    函数的嵌套

    """
    函数的嵌套:一个函数调用了另一个函数
    """
    def test1():
        print('test 1 run')
    def test2():
        print('test 2 run')
        test1()
    test2()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    class:万物皆对象

    构成:类名、属性(一组数据)、方法(函数)

    创建与调用:class name

    # 创建
    class Musician:
        loveMusic = True
    
        def sing(self):
            print('我在唱歌')
    # 调用
    clazz = Musician()
    clazz.sing()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    创建的俩个要素:

    • self参数:
      • self的作用:会在类的实例化中接受传入的数据,在代码中运行
      • 类方法中调用内部属性或者其他方法时,需要使用self来代表实例
      • self属性智慧在方法创建的时候出现,方法调用时就不需要出现
    • 初始化方法(构造函数):
      • 定义初始化方法:def __init__(self),init两边都是下划线
      • __init__()方法,在创建一个对象的时候被默认调用,不需要手动调用
      • 初始化方法中,除了可以设置固定值外,还可以设置其他参数
    class Hero:
        def __init__(self,name,hp,atk,aro):
            # 类方法,用来做变量初始化赋值操作,在实例化的时候会被自动调用
            self.name = name
            self.hp = hp
            self.atk = atk
            self.aro = aro
        def move(self):
            print(self.name,'移动...')
        def attack(self):
            print(self.name,'攻击...')
            print('生命',self.hp)
    
    hero = Hero('xixi',10000,50,20)
    print(hero)
    hero.move()
    hero.attack()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    类的继承

    class Hero:
        def __init__(self,name,hp,atk,aro):
            # 类方法,用来做变量初始化赋值操作,在实例化的时候会被自动调用
            self.name = name
            self.hp = hp
            self.atk = atk
            self.aro = aro
        def move(self):
            print(self.name,'移动...')
        def attack(self):
            print(self.name,'攻击...')
            print('生命',self.hp)
    """
    超级英雄继承英雄类
    """
    class SuperHero(Hero):
        pass
    superHero = SuperHero('超级英雄',1000000,5000,2000)
    superHero.move()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    多重继承与多层继承

    class human:
        def humanSay(self):
            print('我是人类')
    class woman(human):
        def humanSay(self):
            print('我是女人')
        def womanSay(self):
            print('女人')
    class man(human):
        def humanSay(self):
            print('我是男人')
        def manSay(self):
            print('男人')
    class p1(man,woman):
        pass
    p1 = p1()
    p1.manSay()
    p1.womanSay()   
    p1.humanSay()   # 重名的函数会覆盖(重写)父类的方法,先继承的覆盖后面的
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    文件IO

    """
    open()
    r :只读
    w :写入
    a :追加。存在追加,不存在则创建
    rb :二进制打开用于只读
    wb :二进制打开用于写入
    ab :二进制打开用于追加
    r+ :打开文件用于读写。文件指针在文件开头
    w+ :打开文件用于读写。文件存在,则覆盖。否则新建
    a+ :打开文件用于读写。文件存在,指针在尾。否则新建。
    rb+ :以二进制打开文件用于读写。文件指针在头。
    wb+ :以二进制打开文件用于读写。文件存在,则会覆盖。否则新建。
    ab+ :以二进制打开文件用于追加。文件存在,指针在尾。否则新建。
    """
    # open 读入
    file = open('test.txt','r')
    print(file)
    # content = file.read()
    # print('read',content)
    line = file.readline()
    line2 = file.readlines()
    print('readline',line)
    print('readlines',line2)
    file.close()
    
    # write 写出
    newfile = open('newtest.txt','w')
    newfile.write(line)
    newfile.close()
    
    print("=" * 30)
    # with 自动关闭
    with open('test.txt','r') as file:
        data = file.read()
        print(data)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    import语句

    • func.py文件
    def add(a,b):
        return a+b
    
    • 1
    • 2
    from hello.helloEnd import func
    
    res = func.add(1,2)
    print(res)
    
    • 1
    • 2
    • 3
    • 4

    time函数

    import time
    start_time = time.time()
    print(start_time)
    local_time = time.localtime()
    print(local_time)
    print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    csv模块读写

    读取

    import csv
    with open('test.csv','r') as file:
        reader = csv.reader(file)
        print(reader)
        for content in reader:
            print(content)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    写出

    with open('test.csv','a') as file2:
        writer = csv.writer(file2)
        writer.writerow(['xixi2',22,'boy'])
    
    • 1
    • 2
    • 3
  • 相关阅读:
    免费享受企业级安全:雷池社区版WAF,高效专业的Web安全的方案
    FTP服务器:ExpanDrive Mac
    HDR相关文章收集
    基于长短期神经网络的可上调容量PUP预测,基于长短期神经网络的可下调容量PDO预测,LSTM可调容量预测
    低代码与无代码平台的选型建议
    springboot烯烃厂压力管道管理系统java ssm
    【数据结构】直接插入排序 & 希尔排序(一)
    运维监控系统 PIGOSS BSM 拓扑自动发现原理
    Polar bear fishing Privacy Policy
    day49数据库 索引 事务
  • 原文地址:https://blog.csdn.net/qq_40366738/article/details/134478274