• [技术干货] python 异常练习题一例
    # 练习题讲解'''2.  编写用于计算阶乘的JC类,该类有一个compute方法,用于计算阶乘。然后编写一个异常类JCException。当compute方法的参数n的值小于0时,抛出JCException异常,否则正常计算阶乘的值。在调用compute方法时使用try…except…语句明确捕捉JCException异常,并输出异常信息。'''class JCException(Exception):    passclass JC:    def compute(self, n):        if n < 0:            raise JCException('只能计算0或正整数的阶乘!')        if n == 0 or n ==1:            return 1        else:            return n * self.compute(n - 1)jc = JC()print(jc.compute(5))try:    print(jc.compute(-10))except JCException as e:    print(e)运行结果:user@n4uqrebz1tv-machine:~/ghj-1634624131740$ /usr/bin/python /home/user/ghj-1634624131740/demo08.py120只能计算0或正整数的阶乘!user@n4uqrebz1tv-machine:~/ghj-1634624131740$
  • [技术干货] python 自定义异常
    python自定义多个类型的异常练习:vi demo04.py# 捕捉多个异常'''try:    ... ...except 异常类1:    ... ...except 异常类2:    ... ...except 异常类3:'''# 表示操作数或计算结果为负数时抛出的异常class NegativeException(Exception):    pass# 表示操作数为0时抛出的异常class ZeroException(Exception):    passclass SpecialCalc:    def add(self,x,y):        if x < 0 or y < 0:            raise NegativeException('x或y小于0')        return x + y    def sub(self,x,y):        if x - y < 0:            raise NegativeException('x - y 小于0')        return x - y    def mul(self,x,y):        if x == 0 or y == 0:            raise ZeroException('x == 0或y == 0')        return x * y    def div(self,x,y):        return x / ywhile True:    try:        calc = SpecialCalc()        expr = input('请输入要计算的表达式,例如,add(1,2):')        if expr == ':exit':            break;        result = eval('calc.' + expr)        print('计算结果:{:.2f}'.format(result))    except NegativeException:        print('*****负数异常*******')    except ZeroException:        print('*****操作数为0异常******')    except ZeroDivisionError:        print('*****分母不能为0********')    except:        print('*****抛出其他异常******')执行结果:4615302885/demo04.pyhine:~/ghj-1634615302885$ /usr/bin/python /home/user/ghj-1634请输入要计算的表达式,例如,add(1,2):add(-1,0)*****负数异常*******请输入要计算的表达式,例如,add(1,2):add(1,0)计算结果:1.00请输入要计算的表达式,例如,add(1,2):sub(3,5)*****负数异常*******请输入要计算的表达式,例如,add(1,2):mul(1,0)*****操作数为0异常******请输入要计算的表达式,例如,add(1,2):mul(3,5)计算结果:15.00请输入要计算的表达式,例如,add(1,2):div(55,0)*****分母不能为0********请输入要计算的表达式,例如,add(1,2)::exituser@ihvlxz26j2d-machine:~/ghj-1634615302885$ 
  • [技术干货] python setdefault函数用法
    python setdefault函数用法“vi demo12.py#-*- coding=utf-8 -*-# setdefault方法d = {"name":"Bill", "age":30}d['salary'] = 2000d['age'] = 50# Noneprint(d.setdefault("location","中国")) #显示value值print(d)print(d.setdefault("location", "德国")) #显示第一次赋值的value值,并不更新赋值print(d)print(d.setdefault("abc")) #没有赋值,赋值为noneprint(d)个人理解:setdefault设置默认值对,只能赋值一次(也只需要赋值一次),如果没有赋值,none就是赋值。运行结果:634105756450/demo12.pyne:~/fgdf-1634105756450$ /usr/bin/python /home/user/fgdf-16中国{'name': 'Bill', 'age': 50, 'salary': 2000, 'location': '中国'}中国{'name': 'Bill', 'age': 50, 'salary': 2000, 'location': '中国'}None{'name': 'Bill', 'age': 50, 'salary': 2000, 'location': '中国', 'abc': None}user@usqn6b4elnx-machine:~/fgdf-1634105756450$ 
  • [技术干货] python字典数据类型pop方法和popitem方法
    python字典数据类型pop方法和popitem方法练习。pop方法,用于获取指定的key的值,并从字典中弹出这个key-value对;popitem方法用于返回字典中最后一个(类似堆栈)key-value对,并弹出key-value对。vi demo11.pyd = {'c':10,'a':40,'b':12,'x':45}d['1'] = 20d['5'] = 100print(d.pop('a'))print(d)for i in range(len(d)):    print(d.popitem())运行结果:[root@ecs-0720 chapter06]# python demo11.py40{'c': 10, 'b': 12, '1': 20, '5': 100, 'x': 45}('c', 10)('b', 12)('1', 20)('5', 100)('x', 45)[root@ecs-0720 chapter06]# 
  • [技术干货] python字典操作items方法和keys方法
    python字典数据类型操作常使用的items方法和keys方法练习:vi demo10.pyd = {'help':'帮助','bike':'自行车','plane':'飞机','China':'中国'}print(d.items())   #dict_items([('help', '帮助'), ('bike', '自行车'), ('plane', '飞机'), ('China', '中国')])for key_value in d.items():    print("key","=",key_value[0],"value","=",key_value[1])for key,value in d.items():    print("{} = {}".format(key,value)) #两种方法遍历字典中的元素print(('bike','自行车') in d.items()) #in判断字典的item中是否有特定元组dict_items = d.items()d['bike'] = '自行车;摩托车;电动自行车' #更新赋值print(dict_items)print(d.keys())for key in d.keys():    print(key)运行结果:user@gomfa6ektdg-machine:~/dsfad-1634020502892$ python demo10.pydict_items([('help', '帮助'), ('bike', '自行车'), ('plane', '飞机'), ('China', '中国')])key = help value = 帮助key = bike value = 自行车key = plane value = 飞机key = China value = 中国help = 帮助bike = 自行车plane = 飞机China = 中国Truedict_items([('help', '帮助'), ('bike', '自行车;摩托车;电动自行车'), ('plane', '飞机'), ('China', '中国')])dict_keys(['help', 'bike', 'plane', 'China'])helpbikeplaneChinauser@gomfa6ektdg-machine:~/dsfad-1634020502892$ 
  • [技术干货] python通过fromkeys方法新建字典
    python通过fromkeys方法新建字典练习:vi demo08.py# fromkeys方法# 只赋值key的方式构造一个字典newDict1 = {}.fromkeys(['name', 'company', 'salary'])print(newDict1)newDict2 = newDict1.fromkeys(('name', 'company','age'))print(newDict2)newDict3 = newDict1.fromkeys(['name', 'company', 'salary'],'没有值')print(newDict3)运行结果:634019661015/demo08.pyne:~/fgdf-1634019661015$ /usr/bin/python /home/user/fgdf-16{'name': None, 'company': None, 'salary': None}{'name': None, 'company': None, 'age': None}{'name': '没有值', 'company': '没有值', 'salary': '没有值'}user@gomfa6ektdg-machine:~/fgdf-1634019661015$ 
  • [技术干货] python字典数据练习
    python的字典类型数据操作练习:1. 获取字典中key的列表2. 获取字典中key—value对的列表3. 多个列表的并行迭代4. 压缩序列迭代5. 反转序列迭代vi demo04.py# 定义一个字典d = {"name":"Bill", "age":20,"sex":"男", "salary":4567.5}# 迭代字典中的keyfor key in d:    print("{} = {}".format(key, d[key]), end = ' ')print()# 同时迭代字典中的key和valuefor key,value in d.items():    print("{} = {}".format(key, value), end = ' ')# 并行迭代list1 = [1,2,3,4,5]list2 = ['a','b','c','d','e']for i in range(len(list1)):    print("list1[{}] = {}, list2[{}] = {}".format(i,list1[i],i,list2[i]),end = " ")print()# 压缩迭代for value in zip(list1, list2):    print(value, end = " ") #列表中对应数据组成一个元组print()items = []for value in zip(list2, list1):    items.append(value)  #将元组序列构造成一个列表d1 = dict(items) #列表转换成字典print(d1)print()# 反转排序迭代values1 = [4,1,5,6,3,1,7,9]print(sorted(values1))values2 = reversed(values1)for v in values2:    print(v, end = " ")print()# abcdefg  gfedcbaprint(''.join(list(reversed("abcdefg"))))运行结果:634018568728/demo04.pyne:~/fgdf-1634018568728$ /usr/bin/python /home/user/fgdf-16name = Bill age = 20 sex = 男 salary = 4567.5 name = Bill age = 20 sex = 男 salary = 4567.5 list1[0] = 1, list2[0] = a list1[1] = 2, list2[1] = b list1[2] = 3, list2[2] = c list1[3] = 4, list2[3] = d list1[4] = 5, list2[4] = e (1, 'a') (2, 'b') (3, 'c') (4, 'd') (5, 'e') {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}[1, 1, 3, 4, 5, 6, 7, 9]9 7 1 3 6 5 1 4 gfedcbauser@e21geybx2m1-machine:~/fgdf-1634018568728$ 
  • [技术干货] python字典数据类型的应用
    练习python字典数据类型的基本操作:1. 键值key的类型,列表数据类型只能是数字(索引),而字典的key可以是多种类型,如字符串、元组等等。2. 引用列表元素,其索引必须在范围内,否则抛出异常;而字典的key如果不存在,会添加一个key-value对3. 查找成员,列表使用in,直接查找值,字典使用in,查找的是key4.字典由于是类似排序树来存储的,所以查找效率要高于列表和元组vi demo03.py# 字典的基本操作# 通过len函数获取字典的长度items = [1,2,3,4,5]print(len(items))d = {"name":"Bill", "age":43}print(len(d))# 通过key获取和设置字典中的值print(d["name"])d["name"] = "Mary"print(d)#print(items[10])d["salary"] = 5432 #没有,则添加print(d)print(1 in items)print(10 in items)print("name" in d)  #查找key,并且有这个name,结果为trueprint("location" in d) #查找value,结果为falseIDEs = {    'eclipse':    {        'languages':['Java','Python','JavaScript','PHP'],        'organization':'Eclipse基金会'    },        #字典的value还是一个字典数据类型    'visualstudio':    {        'languages':['C#','C++', 'VB.NET'],        'organization':'微软'    },    'webstorm':    {        'languages':['JavaScript'],        'organization':'JetBrains'    }        }labels = {    'languages':'支持的编程语言',    'organization':'所属机构'    }IDE = input('请输入IDE的名字')findIDE = IDE.replace(' ', '').lower()choice = input('要查询的IDE支持的编程语言(lang)还是所属及机构(org)?')if choice == 'lang': key = 'languages'if choice == 'org': key = 'organization'if findIDE in IDEs:    print("{} {}是{}.".format(IDE, labels[key],IDEs[findIDE][key]))使用cloudIDE运行结果:ix-sample-1633932574246/demo03.pyx-sample-1633932574246$ python /home/user/phoeni52Bill{'name': 'Mary', 'age': 43}{'name': 'Mary', 'age': 43, 'salary': 5432}TrueFalseTrueFalse请输入IDE的名字eclipse要查询的IDE支持的编程语言(lang)还是所属及机构(org)?orgeclipse 所属机构是Eclipse基金会.user@pynqqjcg02i-machine:~/phoenix-sample-1633932574246$ /usr/bin/python /home/user/phoenix-sample-1633932574246/demo03.py52Bill{'name': 'Mary', 'age': 43}{'name': 'Mary', 'age': 43, 'salary': 5432}TrueFalseTrueFalse请输入IDE的名字webstorm要查询的IDE支持的编程语言(lang)还是所属及机构(org)?langwebstorm 支持的编程语言是['JavaScript'].user@pynqqjcg02i-machine:~/phoenix-sample-1633932574246$ 
  • [技术干货] python使用dict函数转换成字典
    python中的字典数据类型,方便通过索引查找对应的数据。练习通过dict函数对列表数据转换为字典数据类型的数据。vi demo02.pyitems = [['Bill',"4321"],("Mike","7891"),['John','4567']]d = dict(items)  #直接将列表转换为字典print(d)dict1 = dict(name="Bill", number=6543, age=34) #使用键值赋值的方式转换print(dict1)items = []while True:    key = input("请输入Key:")    if key == ":exit": #退出条件        break;    value = input("请输入value:")    keyValue = [key,value]    items.append(keyValue) #首先构造一个列表d = dict(items) #将列表转换为字典print(d) 使用华为云的cloudIDE运行结果:-1633920136428/demo02.py:~/dsfad-1633920136428$ /usr/bin/python /home/user/dsfad-{'Bill': '4321', 'Mike': '7891', 'John': '4567'}{'name': 'Bill', 'number': 6543, 'age': 34}请输入Key:name请输入value:zhangsan请输入Key:salary请输入value:1000请输入Key:age请输入value:35请输入Key::exit{'name': 'zhangsan', 'salary': '1000', 'age': '35'}user@osq9xh18z6h-machine:~/dsfad-1633920136428$ 
  • [技术干货] python字符串的拼接
    python使用oin函数实现字符串的拼接练习:#demo11.py# -*- coding: utf-8 -*-# 字符串方法:join# 用于连接序列中的元素,split方法list = ["a", "b", "c", "d", "e"]s = '*'print(s.join(list))print("xy".join(list))# C:\abc\xyz# /abc/xyz# c:\usr\local\nginx\# /usr/local/nginx/dirs = '','usr','local','nginx',''linuxPath = '/'.join(dirs)print(linuxPath)windowPath = 'C:' + '\\'.join(dirs)print(windowPath)numList = [1,2,3,4,5,6]print("a".join(numList)) #join连接的只能是字符串,int格式参数会报异常。 运行结果:[root@ecs-0720 ~]# python demo10.pya*b*c*d*eaxybxycxydxye/usr/local/nginx/C:\usr\local\nginx\Traceback (most recent call last):  File "demo10.py", line 24, in <module>    print("a".join(numList))TypeError: sequence item 0: expected string, int found[root@ecs-0720 ~]# 
  • [技术干货] python分割字符串
    使用split函数分割字符串练习:#demo11.py# -*- coding: utf-8 -*-# 字符串方法:split方法s1 = "a b c d e f"print(s1.split())  #将s1根据空格分割成7个字符s2= "a*b*c*d*e" print(s2.split("*")) #将s2根据星号分割成5个字符path = "/usr/local/nginx"pathList = path.split('/')print(pathList) #用反斜杠分割出目录名windowPath = "D:" + "\\".join(pathList) #这里的写法很好,记下。print(windowPath) 运行结果:[root@ecs-0720 ~]# python demo11.py['a', 'b', 'c', 'd', 'e', 'f']['a', 'b', 'c', 'd', 'e']['', 'usr', 'local', 'nginx']D:\usr\local\nginx[root@ecs-0720 ~]# 
  • [技术干货] python字符串处理之大小写转换
    本次使用cloudShell方式远程登录ECS,有一点不大习惯的是使用Vim编辑文件的时候,ecs键不可用,这样就卡在编辑模式退不出来。。。没有找到解决办法,只能换编辑器,好在cloudShell自带的文件处理功能很方便:只需要双击右手侧的文件浏览器中的特定文件,就会报一个安全提示,忽略掉,文件就打开,直接编辑,然后叉掉就保存了。#demo12.py# -*- coding: utf-8 -*-# 字符串方法:lower、upper和capwords函数print("HEllo".lower())   #首先打印小写的helloprint("hello".upper())   #再打印大写的HELLOlist = ["Python", "Ruby", "Java","KOTLIN"]if "Kotlin" in list:    print("找到Kotlin了")else:    print("未找到Kotlin")   #大小写不一致,打印此行for lang in list:    if "kotlin" == lang.lower(): #转换大小写,匹配到。        print("找到Kotlin了")        break;    from string import capwordss = "i not only like Python, but also like Kotlin"print(capwords(s))  #capwords() 方法用来将传入的字符串用 split() 按照空格分隔成序列后,#将序列每项首字母大写后,再使用空格组成字符串返回。#个人理解:格式规整化。    运行结果:[root@ecs-0720 ~]# python demo12.pyhelloHELLO未找到Kotlin找到Kotlin了I Not Only Like Python, But Also Like Kotlin[root@ecs-0720 ~]# 
  • [问题求助] openEuler20.09安装 boost_python* numpy* python36-numpy报错
    【功能模块】在openEuler 20.09系统下安装 依赖包时出错,麻烦看看怎样才能安装这3个依赖包呢?谢谢,在centos 7.6下,可以安装成功。 yum -y install zlib* lapack* blas* python3.aa4 cmake3* boost_python* boost boost-devel numpy* python36-numpy flex bison【操作步骤&问题现象】1、2、【截图信息】【日志信息】(可选,上传日志内容或者附件)
  • [技术干货] python使用replace和strip替换字符串
    python使用replace和strip替换字符串replace()前后两个参数分别是要替换的字符串和替换的字符串。如果找不到要替换的字符串,则返回原字符串。strip()函数功能去掉字符串前后的空格。也可以带参数,去掉特定模式的字符。应用举例:vi demo13.pys = "abcdaedf"print(s.replace("a", "12345"))  #将a替换为12345print(s.replace("xyz","aa")) #找不到xyz,返回原字符串print("   geekori.com   ".strip()) #去除前后的空格print(" <  geekori.com  >  ".strip()) #去除前后的空格,中间的空格不动langList = ["python", "java", "ruby", "scala", "perl"]lang = "   python   "if lang in langList:    print("找到了python")else:    print("未找到python")    #因为lang有空格,查询结果是未找到pythonif lang.strip() in langList:  #去掉空格    print("找到了python")  #查询结果是找到了pythonelse:    print("未找到python")s = "***  $$*  Hello * World   ***$$$  "print(s.strip(" *$")) #去掉特定模式的前后缀,仅保留Hello * World使用华为云的cloudIDE运行上面的代码:633762604641/demo13.pyne:~/fgdf-1633762604641$ /usr/bin/python /home/user/fgdf-1612345bcd12345edf  abcdaedfgeekori.com<  geekori.com  >未找到python找到了pythonHello * Worlduser@onzhrbc3glw-machine:~/fgdf-1633762604641$ 
  • [技术干货] python字符串方法translate和maketrans
    python字符串方法translate和maketrans一般一起使用,translate实现字符串的替换,maketrans用来构造替换字典。应用代码如下:vi demo14.pys = "I not only like python, but also like kotlin."table = s.maketrans("ak", "*$") #将a字符替换为*,k字符替换为$print(table) #显示字典的ascii码字典print(s.translate(table)) #打印替换后的字符串table1 = s.maketrans("ak", "*$", " ") #传递第三个参数用来同步实现删除特定字符串的功能print(table1)print(s.translate(table1))ecs默认安装的是python2.7,运行发现找不到上面的函数。搜资料可以import string来解决。修改上述代码:vi demo14.pyimport strings = "I not only like python, but also like kotlin."table = string.maketrans("ak", "*$")#print(table)print(s.translate(table))table1 = string.maketrans("ak", "*$", " ")#print(table1)print(s.translate(table1))运行结果为:[root@ecs-0720 ~]# python demo14.pyI not only li$e python, but *lso li$e $otlin.Traceback (most recent call last):  File "demo14.py", line 10, in <module>    table1 = string.maketrans("ak", "*$", " ")TypeError: maketrans() takes exactly 2 arguments (3 given)[root@ecs-0720 ~]# 说明string模块中的maketrans函数只支持传递两个参数,而不支持第三个参数。需要找个python 3.4以上的环境试下。首选华为云的IDE环境!从会员中心的日常任务入口进入,随便找个项目。运行结果为:实验完马上关闭IDE,每天15分钟的时间,还是足够用的。:)
总条数:2474 到第 页
上滑加载中