处理异常 - python中的负平方根

ASm*_*ASm 2 python python-3.x

我正在尝试编写一段代码来处理负平方根的例外,因为我只想要一个正结果.我的代码是:

def sqRoot(x):
    try: 
        result = (x)**0.5
    except ValueError:
        result = "This is a negative root"
    except TypeError:
        result = "Please enter a number"
    return result
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当我使用调用运行此代码时

x = sqRoot(-200)
Run Code Online (Sandbox Code Playgroud)

我没有得到错误,而是python给了我一个复数的结果.我似乎无法在代码中看到错误.

srg*_*erg 5

从评论中转移这个讨论......

在Python 3.0中,幂运算符的行为发生了变化.在python的早期版本中,将负数提升为分数幂会引发ValueError异常,但在Python 3中会产生复杂的结果.

查找平方根的另一种方法是python是math.sqrt函数.在Python 3中,当使用负数时,会引发ValueError异常:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.sqrt(-200)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error
Run Code Online (Sandbox Code Playgroud)