Discuss / Python / 完善my_abs函数后还是有问题

完善my_abs函数后还是有问题

Topic source

小核桃cc6

#1 Created at ... [Delete] [Delete and Lock User]

根据老师说的,将my_abs函数完善成下面代码:

def my_abs(x): if not isinstance(x, (int, float)): raise TypeError('bad operand type') if x >= 0: return x else: return -x

在python交互环境中运行,出现:

from abstest import my_abs my_abs('a') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\pythonwork\abstest.py", line 2, in my_abs if not isinstance(x, (int, float)): TypeError: '>=' not supported between instances of 'str' and 'int'

哪里出问题了

你解决了这个问题了吗?我也是这个情况

zhuangyuzzl

#3 Created at ... [Delete] [Delete and Lock User]

未完善myabs前,在python解释器或交互式命令中输入 from abstest import my_abs 会在工作文件夹下生成新的文件夹,以我的举例: D:\work_pycache\abstest.cpython-37.pyc 将pycache文件夹内的 abstest.cpython-37.pyc 删除, 在python解释器或交互式命令中输入 crtl + c exit() 完善my_abs,再进Python,输入 from abstest import my_abs 即可

小核桃cc6

#4 Created at ... [Delete] [Delete and Lock User]

谢谢


  • 1

Reply