gpt4 book ai didi

python - 为什么没有引发 ValueError ?

转载 作者:行者123 更新时间:2023-12-01 08:24:14 25 4
gpt4 key购买 nike

Python 文档指出:

enter image description here

所以我的代码是:

print(pow(-2,2.1))

这段代码应该引发 ValueError,因为 -2 和 2 是有限的,-2 是负数,并且 2.1 不是整数 - 因此 pow(-2,2.1) 是未定义的。

最佳答案

您将内置 pow 函数与 math.pow 的文档混淆了

请参阅此处了解内置 pow 函数: https://docs.python.org/3/library/functions.html#pow

Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z). The two-argument form pow(x, y) is equivalent to using the power operator: x**y.

The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 102 returns 100, but 10-2 returns 0.01. If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative.

还值得注意的是,内置 pow 函数的结果与使用 ** 的结果相同,即pow(-2,2.1) 相当于 (-2) ** 2.1

关于python - 为什么没有引发 ValueError ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54391129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com