Python的快速入门2

python的使用

除了上篇博客介绍的字典列表集合等基本结构还有基本操作之外,还有函数的使用,接下来去介绍python中的包的概念

异常的基本示例

%%writefile li.py
learn = 10
def learn_s(learn_list):
    learn_sum = 0
    for i inrang(len(learn_list))
        learn_sum+=learn_list[i]
    return learn_sum
learn_list = [1,2,3,4,5]
print (learn_s(learn_list))
#执行完此步骤就会出现一个.py文件
#写入一个文件
#执行这个脚本文件
%run li.py
#输出15执行这个脚本文件的结果
#当我们使用这个脚本文件的话需要如下操作
import li.py
print (li.learn)
#输出10
li.learn=100
li.learn#输出100
study_list=[1,2,3,4,5,6]
li.learn_s(study_list)
#输出21
import li as ab
ab.learn_s(study_list)
#依旧输出的是21
from li import learn,learn_s
learn
#输出的是10
learn_s(study_s)
from li import *
import os#执行操作系统的命令
os.remove(li.py)#删除脚本文件

异常处理模块

在java中的异常处理有try-catch

import math
for i in rang ():
    input_number = input('write a number')
    if input_number =='q':
        break
    result = math.log(float(input_number))
    print result
#当输入的值为时就会出现异常,如何解决这些异常呢,我们采用try-except结构来处理改进方法
import math
for i in rang ():
    try:
        input_number = input('write a number')
        if input_number =='q':
            break
        result = math.log(float(input_number))
        print result
    except ValueError:
        print('ValueError: input must >0')
        break
#可以跳出异常
#当我们不知道异常是什么我们可以选择Exception类
for i in rang ():
    try:
        input_number = input('write a number')
        if input_number =='q':
            break
        result = math.log(float(input_number))
        print result
    except ValueError:
        print('ValueError: input must >0')
        break
    except ZeroDivisionError:
        print('ZeroDivisionError')
        break
    except Exception
        print('unknow Exception!')

自定义异常

这边涉及到后边继承的知识,如果读者不清楚类的知识可以暂时跳过

class li(ValueError)
    pass
cur_list = ['li','jia','yy']
while True:
    cur_input = input()
    if cur_input not in cur_list:
        raise LIError('Invalid input%s'%cur_input')
#当我们输出入li的时候没有问题
#但是当我们输入的是zhang就会出现错误

finally的使用

try:
    1/0
finally:
    print('finally')
#无论程序中是否遇到异常都会执行finally
for i in range (100):
    try :
        input_number = input('write a number')
        if input_number =='q':
            break
        result = math.log(float(input_number))
        print (result)
    except ValueError:
        print('ValueError: input must >0')
    finally:
        print('finally')

我们使用的异常处理一般都是使用try-except-finally这个操作

文件的基本操作

先介绍一些基本的操作,然后之后的numpy,pandas只有的再介绍

%%writefile learn.txt
hello python
lijia
jin tian zai xia yu 
#执行此段操作就会在相应的位置出现一个learn.txt文件
#打开此文件就会出现我们刚才写的内容
txt = open (./learn.txt)
txt_read = txt.read()
print(txt_read)
lines = txt.readlines()
print(type(lines))#输出的是一个list结构
#每一句话都是一个列表结构
print(lines)
#输出结果为hello python\nlijia\njin tian zai xia yu 
for line in lines:
   print('cur_line',line)
#输出结果为
#cur_line hello python
#cur_line lijia
#cur_line jin tian zai xia yu 
txt.close()

关于文件的写操作

txt = open(learn.txt,'w')
txt.write('wozhendehaofan')
txt.write('\n')
txt.write('henhao')
txt.close()
#执行完此操作之后就会出现一个问题,出现覆盖掉了原来的内容
txt = open(learn.txt,'a')
txt.write('wozhendehaofan')
txt.write('\n')
txt.write('henhao')
txt.close()
#执行完此操作之后就会追加在文章之后

容易出现的问题

txt = open(learn.txt,'w')
for i in range(100)
    txt.write(str(i)+'\n')
txt2 = open(learn.txt,'r')
print(txt.read())
#如果没有关掉文件就会出现一个问题就是读不出来数据
txt.close()
#这个位置提示我们一个问题就是在稳健操作的时候必须关上文件
这时候就用上了咱们之前介绍的异常处理的模块了
txt = open('learn_txt','w')
try:
    for i in range(100):
        10/(i-5)
except Exception:
    print('error',i)
finally: 
    txt.close()
with open('learn_txt','w') as f
 f.write('jintiantainqihao ')
#with方法可以替你去关闭文件,推荐的操作

python的类

面向对象的思想

class people:
#所有实例都会共享
    number=100
#构造函数,初始化的方法
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def display(self):
       print('number = ',people.number)
    def display(self):
       print('name = ',name)
people.__doc__
#查看类的帮助文档的信息
p1 = people ('lili',15)
p1 = people ('lifei',18)
p1.name
p2.name
p1.display()
p1.name = 'hello'
del p2.name
hasattr(p1,'name')
#查看是否有对应的属性
getattr(p1,'name')#会输出对应的属性的值
setattr(p1,'name','lijiaa')
delattr(p1,'name')

类的属性的基本操作

print(prople.__doc__)
print(prople.__name__)
print(prople.__module__)#属于那个模块这个输出的是main
print(prople.__bases__)#类的父类
print(prople.__dict__)#类的整体组成

关于类的继承

class Person:
    number =100
    def __init__(self):
        print('调用父类的构造函数')
    def parentM(self):
        print('调用父类方法')
    def setAttr(self,attr):
        Parent.parentAttr = attr
    def getAttr(self)
        print('父类属性:',Parent.parentAttr)
    def newM(self):
        print('父类要被重写的方法')
class child(Parent):
    def __init__(self):
        print('调用子类的构造函数')
    def childM(self):
        print('调用子类的构造函数')
    def newM(self):
        print('子类把它覆盖掉了')
c=child()
c.ParentM()
c.setAttr(100)
c.getAttr()
#输出的是
调用子类的构造函数
调用子类的构造函数
调用父类方法
100
c.newM()
#输出的是
子类把它覆盖掉了

时间的使用

import time
print (time.time())
#输出的是从1910年到现在经过了多久
print(time.localtime(time.time()))
#转换成tm_year =2021 ,tm_mon = 10等等
print(time.asctime(time.localtime(time.time())))
#格式化时间戳
print(time.strftime('%Y-%m-%d',time.localtime()))
#输出2121-10-9
import calendar
print(calendae.month(2021,10))
posted @ 2021-10-09 21:44  李家成  阅读(47)  评论(0)    收藏  举报