您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站
  • python学习笔记十:异常

    597 wiki 2022-01-14
    一、语法#!/usr/bin/pythonfilename='hello'#try except finally demotry:open('abc.txt')print helloexcept IOError,msg:print 'the file not exist'except NameError,msg:print 'hello not defined'finally:print 'end'#throw exceptionif filename == "hello":raise TypeError('nothing')二、常见异常类型1、AssertionError:assert语句失败2、AttributeError:试图访问一个对象没有的属性3、IOError:输入输出异常,基本是无法打开文件4、ImportError:无法引入模块或者包,基本是路径问题5、IndentationError:语法错误,代码没有正确对齐6、IndexError:下标索引超出序列边界7、KeyError:试图访问你字典里不存在的键8、KeyboardInterrupt:Ctrl+C被按下9、NameError:使用一个还声明的变量10、SyntaxError:代码逻辑语法出错,不能执行12、TypeError:传入的对象类型与要求不符13、UnboundLocalError:试图问一个还未设置的全局变量,基本上是由于另有一个同名的全局变量14、ValueError:传入一个不被期望的值,即使类型正确
    python Python
  • python学习笔记十一:操作mysql

    608 wiki 2022-01-14
    一、安装MySQL-python# yum install -y MySQL-python二、打开数据库连接#!/usr/bin/pythonimport MySQLdbconn = MySQLdb.connect(user='root',passwd='admin',host='127.0.0.1')conn.select_db('test')cur = conn.cursor()三、操作数据库?def insertdb():sql = 'insert into test(name,`sort`) values ("%s","%s")'exsql = sql % ('hello','python')cur.execute(exsql)conn.commit()return 'insert success'def selectdb():sql = 'select `name` from test where `sort` = "%s"'exsql = sql % ('python')count = cur.execute(exsql)for row in cur:print rowprint 'cursor move to top:'cur.scroll(0,'absolute')row = cur.fetchone()while row is not None:print rowrow = cur.fetchone()print 'cursor move to top:'cur.scroll(0,'absolute')many = cur.fetchmany(count)print manydef deletedb():sql = 'delete from test where `sort` = "%s"'exsql = sql % ('python')cur.execute(exsql)conn.commit()return 'delete success'print insertdb()print insertdb()selectdb()print deletedb()?四、关闭连接cur.close()conn.close()注意顺序。
    python Python
  • python学习笔记五:模块和包

    593 wiki 2022-01-14
    一、模块用import导入cal.py:#!/usr/bin/pythondef add(x,y):return x+yif __name__ == '__main__':print add(1,2)注:__name__为内置变量,如果直接在CLI中调用值为__mail__,否则为文件名。在new.py中导入:import calprint cal.add(2,3);二、包:按目录名组织的模块1、建立一个名字为包名字的文件夹2、在该文件夹下创建一个__init__.py文件3、根据需要在该文件夹下存放脚本文件、已编译的扩展及子包4、在文件中用 import pack.m1,pack.m2,pack.m3 进行导入5、用 pack.m1.xxx来调用包中模块的方法示例目录结构:util/├── cal.py├── cal.pyc├── __init__.py└── __init__.pyc调用示例new.py:import util.calprint util.cal.add(2,3);//5或用as来使用别名:import util.cal as cprint c.add(2,3);//5或者用from来简写:from util.cal import addprint add(2,3);
    python Python
  • python学习笔记七:浅拷贝深拷贝

    592 wiki 2022-01-14
    原理?浅拷贝import copyb = copy.copy(a)demo:>>> a=[1,['a']]>>> b=a>>> c=copy.copy(a)>>> a[1, ['a']]>>> b[1, ['a']]>>> c[1, ['a']]>>> id(a)140556196249680>>> id(b)140556196249680>>> id(c)140556298139120>>> a[0]=2>>> a[2, ['a']]>>> c[1, ['a']]>>>a[1].append('b')>>>a[2,['a','b']]>>>c[1,['a','b']]深拷贝import copyb = copy.deepcopy(a)demo:>>> a=[1,2,['a','b']]>>> b=copy.deepcopy(a)>>> a[1, 2, ['a', 'b']]>>> b[1, 2, ['a', 'b']]>>> id(a)140556196175952>>> id(b)140556196501336>>> id(a[0])11961144>>> id(b[0])11961144>>> id(a[2])140556196424448>>> id(b[2])140556196250472>>> a[0]=3>>> a[2].append('c')>>> a[3, 2, ['a', 'b', 'c']]>>> b[1, 2, ['a', 'b']]
    python Python
  • python学习笔记四:lambda表达式和switch

    601 wiki 2022-01-14
    一、定义lambda arg1,arg2... : returnValue二、示例#!/usr/bin/pythondef f(x,y):return x*yprint f(2,3)#6g = lambda x,y:x*yprint g(2,3)#6三、switch的一种实现方案#!/usr/bin/pythonfrom __future__ import division#a=int(raw_input('please input num1:'))#b=int(raw_input("please input num2:"))def jia(x,y):return x+ydef jian(x,y):return x-ydef cheng(x,y):return x*ydef chu(x,y):return x/ydef operator(x,o,y):if o == '+':print jia(x,y)elif o == '-':print jian(x,y)elif o == '*':print cheng(x,y)elif o == '/':print chu(x,y)else:passoperatord = {'+':jia,'-':jian,'*':cheng,'/':chu}def switchoperator(x,o,y):print operatord.get(o)(x,y)operator(2,'+', 4)operator(2,'-', 4)operator(2,'*', 4)operator(2,'/', 4)switchoperator(2,'+', 4)switchoperator(2,'-', 4)switchoperator(2,'*', 4)switchoperator(2,'/', 4)
    python Python
  • java如何实现python的urllib.quote(str,safe='/')

    615 wiki 2022-01-14
    最近需要将一些python代码转成java,遇到url编码 urllib.quote(str,safe='/') 但java中URLEncoder.encode(arg, Consta
    python Python
  • Windows系统下在Eclipse中集成Python

    596 wiki 2022-01-14
    我现在偶尔开发代码,已经不用Eclipse了,主要原因是查看Jar包中的代码反编译十分不便,项目加载的时候卡,偶尔还会崩溃用Intellij IDEA和PyCharm??原来的笔记如何在Eclipse中集成Python贴在here# 安装python* 下载python 安装包* 安装并配置环境变量 D:Python3;# Eclipse 集成pydev* 添加 pydev插件,Preferences -> Install / Update -> addlocation: http://pydev.org/updates* 安装插件 help -> install new software
    python Python
  • 再困难的问题,都有迹可循。

    633 wiki 2022-01-14
    报错:_tkinter.TclError: cannot use geometry manager pack inside . which already has slaves managed by grid原因:一个程序中,只能使用一种布局,否则会报上面的错误。几何方法描述pack()包装;grid()网格;place()位置;
    python Python
  • python(day17)二分查找

    572 wiki 2022-01-14
    l = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31]def find(l ,aim ,start = 0,end = None):end = len(l) if end is None else end #end的问题解决mid_index = ( end - start )//2 + start #中间数下标问题的解决if start <=end: #找不到问题的解决if l[mid_index]<aim:return find(l ,aim ,start = mid_index+1,end = end )elif l[mid_index]>aim:return find(l,aim, start = start,end = mid_index - 1)else:return mid_indexelse:return '没有找到'#l = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31]ret = find(l,27)print(ret)#注意,是len(l),还有end = end ,start = start,+1-1要注意
    python Python
  • DAY14(PYTHONS)生成器进阶

    613 wiki 2022-01-14
    def average():sum = 0count = 0avg = 0while True: #循环num = yield avg #遇到yield就停止,防止一开始除数为0导致崩溃sum += numcount +=1avg = sum/countavg_g = average() #生成器获取avg_g.__next__() #执行生成器的__next__()函数,跳到第一个yield之后avg1 = avg_g.send(10) #执行生成器的send()函数,把10带入num,开始执行并返回avgavg2 = avg_g.send(20)print(avg1,avg2)千万注意缩进,刚开始我while True:下面没缩进,就导致代码错误,正确输出如下:10.0 15.0?下图是添加了装饰器,以及程序的执行步骤
    python Python
  • 登陆三次验证(二)

    588 wiki 2022-01-14
    usename = input('请输入你的注册账号')passward = input('请输入你的注册密码')with open('list_of_info',mode='w+',encoding="utf-8") as f:f.write("{}n{}".format(usename,passward))print("恭喜你注册成功")i=0lis=[]while i<3:usn = input('请输入你的登录账号')pwd = input('请输入你的登录密码')with open('list_of_info',mode='r+',encoding="utf-8") as f1:for line in f1:lis.append(line)if usn==lis[0].strip() and pwd ==lis[1].strip():print("恭喜你登陆成功")breakelse:print("对不起,你的号码密码错误")i+=1注意:换行符n
    python Python
  • day11(python)装饰器

    615 wiki 2022-01-14
    def wrapper(f):#1def inner(*args,**kwargs):#3ret = f(*args,**kwargs)#5return ret#8return inner#4@wrapper #装饰器名字 #func=wrapper(func),此时func实际上是inner的内存地址def func(*args,**kwargs):#2 #被装饰函数print(args,kwargs)#6print(kwargs)#7func(1,5,6,a=2,b=1)装饰器固定格式如上注意:print()里面不能放**kwargs然后print(args,kwargs)输出的是元祖和字典
    python Python
  • python之lambda表达式

    622 wiki 2022-01-14
    我们先来看一个函数>>>defds(x):return2*x+1>>>>>>ds(5)11lambda表达式省去了定义函数的过程>>>g=lambdax:2*x+1>>>g(5)11简单的两行函数定义变成了一行,让我们的程序变得更加简洁例题:当有两个参数时我们应该怎么改呢>>>defadd(a,b):return
    python Python
  • DAY4(PYTHON)列表的嵌套,range,for

    592 wiki 2022-01-14
    li=['a','b','开心','c']print(li[2].replace ( ' 心 ', ' kaixin ' ) )输出:'a','b','开kaixin','c'li= ['abctai','sfasf','safsa',['sfa','sed',89],23]li [3][1]=li [3][1].upper()print(li)输出: li= ['abctai','sfasf','safsa',['STA','sed',89],23]元祖:只读列表,可循环查询,可切片tu=(1, 2, 3, 'demo', [2,2,4,'taibao'], 'abc')print(tu[0:4])123demo?列表转化成字符串? list--->str?? joins='alex's1='_'.join(s)print(s1)输出:a_l_e_x(join接的是连接)#rangefor i in range(0,10):print ( i )输出:0123456789#for i in range (0,10,3):print (?i )输出:0369
    python Python
  • DAY5(PYTHON) 字典的增删改查和dict嵌套

    588 wiki 2022-01-14
    一、字典的增删改查1 dic={'name':'hui','age':17,'weight':168}2 dict1={'height':180,'sex':'b','class':3,'age':16}3 #print(dic.pop('height','没有返回值')) #删除,如果存在就删除,不存在,就有返回值,del()只能定点删除4 #print(dic.popitem()) #随机删除,有返回值,元祖里是被删除的键值5 #print(dict1.update(dic)) #有就覆盖,没有就添加6 #dic.clear() #清空字典7 #print(dict1)8 #for i in dic.items():#打印出元祖9 # #print(i)10 for k,v in dic.items():#打印出的键值没有括号和逗号11 print(k,v)二、打印出数字数组个数info=input('>>>')for i in info:if i.isalpha():info=info.replace(i," ")l=info.split()print(len(l))
    python Python
  • django+ajax用FileResponse文件下载到浏览器过程中遇到的问题

    690 wiki 2022-01-14
    问题:公司的需求是从mongodb中查找数据并下载回本地,但是在将文件从mongodb通过django服务端,然后从django服务端向浏览器下载文件。但是在下载的时候出了些问题。由于是用的ajax请求,异步的,所以在将文件返回到前端的时候,前端的script标签中的success回调函数中有数据,且是string类型。解决办法:在回调函数中设置重定向到文件所在的url?——代码——django下载文件到浏览器:from django.http import FileResponsedef filedownload(request,filepath):file = open(filepath, 'rb')response = FileResponse(file)response['Content-Type'] = 'application/octet-stream'response['Content-Disposition'] = 'attachment;filename="example.tar.gz"'return response?前端script标签中的ajax请求:<script>$(".sub").on("click", function () {$.ajax({url: "/download",type: "post",data: {id1: $("#id1").val(),id2: $("#id2").val(),start_date: $("#start_date").val(),end_date: $("#end_date").val(),},success: function (data) {var path = data.path;location.href = path # 重定向到文件所在的路径}})});</script>
    python Python
  • python:线程

    611 wiki 2022-01-14
    线程1,线程与进程进程:执行中的程序。进程可以处理一个任务。对于一个人来说一个人就是一个进程。进程被包含着线程。线程:轻量级的进程。一个时间点只做一件事。一个人可以做的多件事情,每一件事情都是一个线程。2,线程是CPU调度的最小单位。进程是资源分配的最小单位3,开启线程的时空开销 都比 开启进程要小,且cpu在线程之间切换比在进程之间切换快。4,一个程序中 可以同时有多进程和线程1)调用模块开启线程import osimport timefrom threading import Threaddef func(): # 子线程time.sleep(1)print('hello world',os.getpid())thread_lst = []for i in range(10):t = Thread(target=func)t.start()thread_lst.append(t)[t.join() for t in thread_lst]print(os.getpid()) # 主线程2)调用类开启线程import osimport timefrom threading import Threadclass MyThread(Thread):count = 0 # 静态属性def __init__(self,arg1,arg2):super().__init__()self.arg1 = arg1self.arg2 = arg2def run(self):MyThread.count += 1time.sleep(1)print('%s,%s,%s,%s'%(self.arg1,self.arg2,self.name,os.getpid()))for i in range(10):t = MyThread(i,i*'*')t.start()print(t.count)
    python Python
  • python3根据地址批量获取百度地图经纬度

    616 wiki 2022-01-14
    python3代码如下:import requestsimport timedef get_mercator(addr):url= 'http://api.map.baidu.com/geocoder/v2/?address=%s&output=json&ak=************************&callback=showLocation'%(addr)response = requests.get(url)return response.textdef TXTRead_Writeline(src,dest):ms = open(src,encoding='utf-8')for line in ms.readlines():with open(dest,"a",encoding='utf-8') as mon:loc=get_mercator(line)mon.write(loc)mon.write("n")time.sleep(1)TXTRead_Writeline("D:Data\test.txt","D:Data\result.txt")
    python Python
  • python 字符串转字节数组

    598 wiki 2022-01-14
    场景:java加解密和python加解密互转的时候,因一些非显示字符无法确认两者是否一致,故需要打出他们的十六进制字节数组进行比较1.python代码实现str='123';print str.encode('hex')结果显示:3132332. java实现String str="123";StringBuffer sbf=new StringBuffer();for(int i=0;i<str.length();i++){Integer tmp=(int)str.charAt(i);sbf.append(Integer.toHexString(tmp));}System.out.println(sbf.toString());
    python Python
  • No module named Crypto--转

    601 wiki 2022-01-14
    https://blog.csdn.net/lacoucou/article/details/53152122背景:win10+python 2.7在python 中使用AES算法时,会报告上述错误,原因是Crypto并非标准模块,需要自己单独安装。安装方法:1.pip install pycropt 这中办法经常会报错:error: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat). Get it from http://aka.ms/vcpython27似乎也很麻烦。2.使用编译好的安装包。下载地址:[pycropt](http://www.voidspace.org.uk/python/modules.shtml#pycrypto)根据自己的版本现在对应的安装即可。然而,安装完,或许并没有什么卵用,使用依旧报错:No module named Crypto.Cipher经过苦苦搜索,终于在stackover上找到答案:?打开链接之后请拉到最后一条回答I found the solution. Issue is probably in case sensitivity (on Windows).?Just change the name of the folder:?C:Python27Libsite-packagescrypto?to: C:Python27Libsite-packagesCrypto翻译过来就是:?把crypto文件夹重命名为Crypto。?终于可以正常使用了。
    python Python

联系我
置顶