• Python重要语法回顾-2-流程控制(顺序、选择、循环)、函数、包、异常、文件操作、类、时间


    8、Python判断结构

    判断结构

    hza = 100
    if hza < 100:
        print('小于100')
    else:
        print('大于100')
    
    • 1
    • 2
    • 3
    • 4
    • 5

    大于100

    hza = 110
    if hza > 200:
        print('%d大于200' % hza)
    elif hza<100:
        print('%d小于100' % hza)
    else:
        print('%d在100~200之间' % hza)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    110在100~200之间

    hza = [123,456,789]
    x = 123
    if x in hza:
        print('%d 在hza内'%x)
    else:
        print('%d 不在hza内'%x)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    123 在hza内

    hza = {'han':123, 'zhuan':456}
    x = 'han1'
    if x in hza:
        print('%s 在hza中' %x)
    else:
        print('%s 不在hza中' %x)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    han1 不在hza中

    9、Python循环结构

    while循环

    n = 0
    while n<10:
        print(n,end=' ')
        n += 1
    
    • 1
    • 2
    • 3
    • 4

    0 1 2 3 4 5 6 7 8 9

    hzas = {'han','zhu','an'}
    # 只要集合不为空 就返回True 继续循环
    while hzas:
        hza = hzas.pop()
        print(hza)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    an
    han
    zhu

    for循环

    hzas = {'han','zhu','an'}
    for name in hzas:
        print(name)
    
    # for循环遍历集合
    
    • 1
    • 2
    • 3
    • 4
    • 5

    an
    han
    zhu

    for i in range(10):
        print(i,end=" ")
    
    # range(10)=>[0,10)=>[0,9]
    
    • 1
    • 2
    • 3
    • 4

    0 1 2 3 4 5 6 7 8 9

    hza = [123,456,678,33,44,1234,980,211,985,1,10,63]
    for i in range(len(hza)):
        print(hza[i],end=" ")
    
    # 遍历普通list方式
    
    • 1
    • 2
    • 3
    • 4
    • 5

    123 456 678 33 44 1234 980 211 985 1 10 63

    hza = [10,11,12,13,14,16]
    for i in hza:
        if i%2==0:
            print(i,end=' ')
        else:
            continue
        print('偶数')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    10 偶数
    12 偶数
    14 偶数
    16 偶数

    hza = [10,11,12,13,14,16]
    for i in hza:
        if i%2==0:
            print(i,end=' ')
        else:
            break
        print('偶数')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    10 偶数

    10、Python函数

    def add_ab(a,b):
        print (a+b)
    
    add_ab(5,6)
    
    • 1
    • 2
    • 3
    • 4

    11

    def add_ab(a,b):
        return (a+b)
    
    x = add_ab(5,6)
    x
    
    • 1
    • 2
    • 3
    • 4
    • 5

    11

    # 函数参数提供默认值
    def add_ab(a=1,b=2):
        return (a+b)
    
    x = add_ab(5,6)
    print(x)
    y = add_ab()
    # 不给参数 参数就是默认值
    y
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    11
    3

    print(add_ab(3,b=10))
    # 这么也行
    
    • 1
    • 2

    13

    # 可变参数函数
    def add_nums(a,*args):
        for i in args:
            a += i
        return a
    x = add_nums(1,2,3,4)
    print(x)
    add_nums(1,2,3,4,5)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    10
    15

    # 可变参数是键值对 
    # 并如何方便地遍历键值对
    def add_nums2(a,**kvargs):
        for key,value in kvargs.items():
            print(key,value) #直接打印2个参数
    add_nums2(1,x=3,y=4,z=5)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    x 3
    y 4
    z 5

    # 可以直接返回多个返回值
    def max_min(*arr):
        a = max(arr)
        b = min(arr)
        return a,b
    
    a,b = max_min(3,4,9,0,19,23,12)
    print(a,b)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    23 0

    # 可以直接返回多个返回值
    
    '''
    def max_min2(*arr):
        return max(arr)
        return min(arr)
    
    a,b = max_min2(3,4,9,0,19,23,12)
    print(a,b)
    '''
    # 报错 不能这么分别返回 只能有一个return
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    TypeError Traceback (most recent call last)
    Input In [18], in () 3 return max(arr) 4 return min(arr) ----> 6 a,b = max_min2(3,4,9,0,19,23,12) 7 print(a,b)

    TypeError: cannot unpack non-iterable int object

    11、Python包

    %%writefile hza.py
    #声明要生成一个.py的脚本文件
    
    hza_v = 10
    #定义一个变量值
    
    def hza_add(hza_list):
        hza_sum=0
        for i in hza_list:
            hza_sum +=i
        return hza_sum
    
    hza_list=[1,2,3,4,5]
    print(hza_add(hza_list))
    input()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Writing hza.py

    %run hza.py
    # 执行脚本
    
    • 1
    • 2

    15

    import hza
    #导入脚本 第一次导入会自动帮你执行一遍
    
    • 1
    • 2

    15

    import hza
    #不会重复导入执行了
    
    • 1
    • 2
    hza
    
    • 1

    print(hza.hza_v)
    # 获取脚本内的变量
    
    • 1
    • 2

    10

    # 修改脚本内变量值
    hza.hza_v=100
    hza.hza_v
    
    • 1
    • 2
    • 3

    100

    hza_list=[10,20,30]
    hza.hza_add(hza_list)
    # 脚本名.函数名  形式调用脚本内的函数
    
    • 1
    • 2
    • 3

    60

    import hza as h
    #导入并取别名 方便调用
    
    • 1
    • 2
    h.hza_v
    
    • 1

    100

    h.hza_add([1,2,3,4,5,6,7,8,9,10])
    
    • 1

    55

    from hza import hza_v,hza_add
    # 导入后不用 .函数名形式  直接可以调用 
    
    • 1
    • 2
    hza_v
    
    • 1

    100

    hza_add([1,2,3])
    
    • 1

    6

    from hza import *
    #所有东西全部导入
    
    • 1
    • 2
    import os
    os.remove('hza.py')
    #删除脚本 本地文件也删除了
    
    • 1
    • 2
    • 3
    hza_v
    # 能用 内存里还有此脚本 说明只是删除了本地文件
    
    • 1
    • 2

    100

    os.path.abspath('.')
    #当前环境的本地目录
    
    • 1
    • 2

    ‘E:\data\ProjectData\JupyteNotebook\01-hello’

    12、Python异常

    import math
    
    for i in range(10):
        n = input('write a number:')
        if n == 'q':
            break
        res = math.log(float(n))
        print (res)
    
    # 接受10次输入 
    # 输入'q'可以提前结束
    # 正常输入正数,打印 ln(n)
    # 输入0,-1 数学错误,触发异常
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    write a number:1
    0.0
    write a number:10
    2.302585092994046
    write a number:2
    0.6931471805599453
    write a number:2.718281828459045
    1.0
    write a number:-1


    ValueError Traceback (most recent call last)
    Input In [3], in ()
    5 if n == ‘q’:
    6 break
    ----> 7 res = math.log(float(n))
    8 print (res)
    ValueError: math domain error

    # 自己捕获异常
    import math
    
    for i in range(10):
        try:
            n = input('write a number:')
            if n == 'q':
                break
            res = math.log(float(n))
            print (res)
        except ValueError:
            print ('ValueError: input must > 0')
    
    # 捕获了异常的好处 程序不会被中断, 还能继续往下执行
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    write a number:1
    0.0
    write a number:2
    0.6931471805599453
    write a number:0
    ValueError: input must > 0
    write a number:-1
    ValueError: input must > 0
    write a number:2.718281828459045
    1.0
    write a number:q

    # 其他异常
    import math
    
    for i in range(10):
        try:
            n = input('write a number:')
            if n == 'q':
                break
            res = 1/math.log(float(n))
            print (res)
        except ValueError:
            print ('ValueError: input must > 0')
        except ZeroDivisionError:
            print ('ValueError: input can not = 1 because can not division by zero')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    write a number:2
    1.4426950408889634
    write a number:1
    ValueError: input can not = 1 because can not division by zero
    write a number:2.718281828459045
    1.0
    write a number:q

    # 其他异常
    import math
    
    for i in range(10):
        try:
            n = input('write a number:')
            if n == 'q':
                break
            res = 1/math.log(float(n))
            print (res)
        except Exception:
            print ('Has some Exception')
    # 捕获所有种类异常 一种处理方式
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    write a number:1
    Has some Exception
    write a number:-1
    Has some Exception
    write a number:2
    1.4426950408889634
    write a number:q

    # 其他异常
    import math
    
    for i in range(10):
        try:
            n = input('write a number:')
            if n == 'q':
                break
            res = 1/math.log(float(n))
            print (res)
        except ValueError:
            print ('ValueError: input must > 0')
        except ZeroDivisionError:
            print ('ValueError: input can not = 1 because can not division by zero')
        except Exception:
            print ('Unknow Exception')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    write a number:0
    ValueError: input must > 0
    write a number:1
    ValueError: input can not = 1 because can not division by zero
    write a number:w
    ValueError: input must > 0
    write a number:asads
    ValueError: input must > 0
    write a number:q

    自定义异常

    • 类 (需要用到简单类的概念)
    class HzaError(ValueError):
        pass
    # 自定义了一个异常类 继承自ValueError
    
    cur_list = ['han','zhu','an']
    while True:
        cur_input = input()
        if cur_input not in cur_list:
            raise HzaError('Invalid input: %s' %cur_input)
            
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    han
    HAN


    HzaError Traceback (most recent call last)
    Input In [3], in ()
    7 cur_input = input()
    8 if cur_input not in cur_list:
    ----> 9 raise HzaError(‘Invalid input: %s’ %cur_input)

    HzaError: Invalid input: HAN

    finally 关键字

    for i in range(4):
        try:
            b=int(input())
            a=2/b
            print(a)
        except:
            print('exception: ==0')
        finally:
            print('finally: 不管有无异常,finally一定会执行')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    1
    2.0
    finally: 不管有无异常,finally一定会执行
    2
    1.0
    finally: 不管有无异常,finally一定会执行
    0
    exception: ==0
    finally: 不管有无异常,finally一定会执行
    4
    0.5
    finally: 不管有无异常,finally一定会执行

    13、Python文件操作

    原生Python操作文件

    • 原生python操作文件也常用
    • 后面numpy,pandas 等包操作也常用
    %%writefile hza.txt
    #use python crate a txt file
    hello Python
    han zhu an
    CV cong cong cong
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Overwriting hza.txt

    txt = open('./hza.txt')
    
    • 1
    # 一次读取所有内容
    txt_read = txt.read()
    print(txt_read)
    
    • 1
    • 2
    • 3

    #use python crate a txt file
    hello Python
    han zhu an
    CV cong cong cong

    # 设法一行行读取
    txt = open('./hza.txt')
    lines = txt.readlines()
    print (type(lines))
    # 发现lines是一个list 多好 一行一个list项
    print (lines)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6


    [‘#use python crate a txt file\n’, ‘hello Python\n’, ‘han zhu an\n’, ‘CV cong cong cong\n’]

    for line in lines:
        print(line,end='')
    
    • 1
    • 2

    #use python crate a txt file
    hello Python
    han zhu an
    CV cong cong cong

    # 读完记得关闭文件
    txt.close()
    
    • 1
    • 2
    # 读文件小结
    txt = open('./hza.txt')
    lines = txt.readlines()
    for line in lines:
        print(line,end='')
    txt.close()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    #use python crate a txt file
    hello Python
    han zhu an
    CV cong cong cong

    Python 写文件

    txt = open('hza_w.txt','w')
    txt.write('jin tian ting hao\n')
    txt.write('han zhu an')
    txt.close()
    # 当前目录下查看真的有文件  内容也写好了
    
    • 1
    • 2
    • 3
    • 4
    • 5
    txt = open('./hza_w.txt')
    print(txt.read())
    txt.close()
    
    • 1
    • 2
    • 3

    jin tian ting hao
    han zhu an

    txt = open('hza_w.txt','w')
    # 'w'是覆盖写入 每次open(..'w') 会清空文件的
    txt.write('123\n')
    txt.write('456')
    txt.close()
    
    txt = open('./hza_w.txt')
    print(txt.read())
    # 发现原来内容没了  只有本次新写入的内容了
    txt.close()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    123
    456

    txt = open('hza_w.txt','a')
    # 'a'是追加写入 每次open(..'a') 不会清空文件的
    txt.write('\nhan\n')
    txt.write('zhuan')
    txt.close()
    
    txt = open('./hza_w.txt')
    print(txt.read())
    # 发现文件原本的内容还在 新的内容追加在后面
    txt.close()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    123
    456
    han
    zhuan

    txt = open('hza_w.txt','w')
    for i in range(5):
        txt.write(str(i)+'\n')
    # 写完后不关闭 文件直接读 能否读到?
    txt2=open('hza_w.txt','r')
    print(txt2.read())
    
    # 新版Python也能读到了  
    # 不过有时执行也可能读不到,很正常 写后不关 OS肯定认为未写完 文件还在写 你又怎么能读呢?  经典'写后读' 数据相关(同步问题)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    txt = open('hza_w.txt','w')
    for i in range(5):
        txt.write(str(i)+'\n')
    txt.close()
    # 写完后关闭了文件
    txt2=open('hza_w.txt','r')
    print(txt2.read())
    # 新版Python也能读到了
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    0
    1
    2
    3
    4

    txt=open('hza_write.txt','w')
    try:
        for i in range(100):
            a = 10/(i-50)
            txt.write(str(a)+'\n')
    except Exception:
        print ('error:',i)
    finally:
        txt.close()
        # 一定要关闭 尤其是发生了异常时 (所以finally很好 不管前面执行得怎样,都会执行close())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    error: 50

    ### with 打开文件 不用手动关闭文件了  执行完with会自动帮你关闭
    with open('hza_write.txt','w') as f:
        f.write('han zhu an\n')
        f.write('han mian ying qiang\n')
    
    • 1
    • 2
    • 3
    • 4

    简单文件就这么读 复杂文件操作 就用工具包了

    14、Python类

    类:面向对象

    class people:
        '帮助信息: 此处可以写类的说明文档 [不难看出,其实就是内置了一个属性而已]'
        #成员变量 (python直接这个写 默认是静态成员 所有类对象共享一份)
        number = 100
        # 构造函数(也是 新建对象时初始化 一定会执行) self相当于this关键字   [注意__init__ 前后都两个下划线]
        def __init__(self,name,age):
            self.name=name
            self.age=age
        # 2个普通成员方法
        def display_number(self):
            print ('number = ',people.number) #self.number 也行
        def display_name(self):
            print ('name = ',self.name)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    people.__doc__
    
    • 1

    ‘帮助信息: 此处可以写类的说明文档 [不难看出,其实就是内置了一个属性而已]’

    # 实例化对象 很简单 (self不用传参)
    p1=people('hza',23)
    p2=people('hmyq',24)
    # 调用对象方法
    p1.display_number()
    p2.display_number()
    p1.display_name()
    p2.display_name()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    number = 100
    number = 100
    name = hza
    name = hmyq

    print(p2.name)
    print(p1.number)
    people.number
    
    • 1
    • 2
    • 3

    hmyq
    100
    100

    # 修改属性值
    p1.name='python'
    p1.name
    
    • 1
    • 2
    • 3

    ‘python’

    删除属性

    del p1.name
    
    • 1
    p1.name
    
    • 1

    AttributeError Traceback (most recent call last)
    Input In [19], in ()
    ----> 1 p1.name

    AttributeError: ‘people’ object has no attribute ‘name’

    判断对象是否有 指定属性

    hasattr(p2,'name')
    
    • 1

    True

    hasattr(p2,'sex')
    
    • 1

    False

    hasattr(p1,'name')
    # 刚刚被删了该属性 应该也是没有
    
    • 1
    • 2

    False

    (python自带全局)get/set方法获取和修改属性值

    getattr(p2,'name')
    
    • 1

    ‘hmyq’

    setattr(p2,'name','tony')
    
    • 1
    getattr(p2,'name')
    
    • 1

    ‘tony’

    delattr方法删除属性

    delattr(p2,'name')
    
    • 1
    getattr(p2,'name')
    
    • 1

    AttributeError Traceback (most recent call last)
    Input In [28], in ()
    ----> 1 getattr(p2,‘name’)
    AttributeError: ‘people’ object has no attribute ‘name’

    python类几个内置属性

    print(people.__doc__)    # 类说明文档
    print(people.__name__)   #类名
    print(people.__module__) # 类所属模块
    print(people.__bases__)  # 类的父类
    print('\n',people.__dict__) # 类的整个结构都打印出来了  (称为字典结构)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    帮助信息: 此处可以写类的说明文档 [不难看出,其实就是内置了一个属性而已]
    people
    main
    (,)

    {‘__module__’: ’ __main__ ', ‘__doc__’: ‘帮助信息: 此处可以写类的说明文档 [不难看出,其实就是内置了一个属性而已]’, ‘number’: 100, ‘__init__’: , ‘display_number’: , ‘display_name’: , ‘__dict__’: , ‘__weakref__’: }

    类的继承

    class Parent: #定义父类
        number = 100 #直接方法外面写就是全局变量(静态变量)
        def __init__(self):
            print('父类构造方法')
        def parentM(self):
            print('父类普通成员方法')
        # python定义 普通成员变量(局部变量 非静态属性) 得用函数定义、或者说直接写setXXX方法就是定义普通属性
        def setAttr(self,attr):
            Parent.parentAttr=attr
        def getAttr(self): #getXXX方法获取属性
            print ('父类属性:',Parent.parentAttr)
        def overrideM(self): # self参数都写上 别丢了
            print ('父类方法,等待被重写')
    
    class child(Parent): #定义子类child 继承自父类Parent
        def __init__(self):
            print ('子类构造方法')
        def childM(self):
            print('子类普通成员方法')
        def overrideM(self): 
            print('子类重写了后的方法')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    # 实例化几个子类对象 并调用 自己的 和 继承自父类 的方法
    c = child() # 创建子类对象 会调用子类构造方法
    c.childM()  # 调用子类自己的普通成员方法 
    c.parentM() # 子类调用父类普通成员方法 (继承下来了 能调用)
    c.setAttr(18) # 也是子类调父类普通成员方法  子类使用父类非局部成员属性 (继承下来了)   
    c.getAttr()  # 上行设置属性值 本行打印属性值
    c.overrideM() # 子类重写父类方法 调用的就是子类方法了
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    子类构造方法
    子类普通成员方法
    父类普通成员方法
    父类属性: 18
    子类重写了后的方法

    15、Python时间

    import time
    
    • 1
    time.time() # 1970-1-1到现在的浮点秒数 时间戳 
    
    • 1

    1661524974.162104

    # localtime方法自动转换 
    time.localtime(time.time())
    
    • 1
    • 2

    time.struct_time(tm_year=2022, tm_mon=8, tm_mday=26, tm_hour=22, tm_min=44, tm_sec=5, tm_wday=4, tm_yday=238, tm_isdst=0)

    struct_time = time.localtime(time.time())
    time.asctime(struct_time)
    
    • 1
    • 2

    ‘Fri Aug 26 22:45:49 2022’

    自定义格式时间

    time.localtime()
    
    • 1

    time.struct_time(tm_year=2022, tm_mon=8, tm_mday=26, tm_hour=22, tm_min=48, tm_sec=5, tm_wday=4, tm_yday=238, tm_isdst=0)

    time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
    
    • 1

    ‘2022-08-26 22:48:50’

    time.strftime('%Y年%m月%d日 %H:%M:%S',time.localtime())
    
    • 1

    ‘2022年08月26日 22:49:16’

    Python 强大的日历类

    import calendar as cal
    print(cal.month(2022,8))
    print(cal.month(2022,9))
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    # 不会用可以查看文档
    print(calendar.__doc__)
    
    • 1
    • 2

    在这里插入图片描述

    # 更好的文档:查看具体方法如何使用
    print(help(calendar.month))
    
    • 1
    • 2

    在这里插入图片描述

  • 相关阅读:
    JS-水果库存记录实现全选全不选功能
    LeetCode 94 Java 实现
    【ESP32】10.PCF8591数模转换器实验(IIC总线/wire库)
    技能大赛试题剖析:文件上传渗透测试
    HOW - CSS 常见效果实现
    大厂排兵布阵NFT
    Linux驱动开发(二)---驱动与设备的分离设计
    如果一个集合的Lebesgue测度为0, 那么它的自己也是Lebesgue可测的并且其测度也为0.
    如何定义 Spring Boot 过滤器?
    Cat Online Judge 判题系统
  • 原文地址:https://blog.csdn.net/hza419763578/article/details/126553781