Python 3.2.3 ValueError:无法将字符串转换为浮点
当我输入pi或任何带有pi的值作为角度提示的答案时,我得到以下错误:Python 3.2.3 ValueError:无法将字符串转换为浮点,python,Python,当我输入pi或任何带有pi的值作为角度提示的答案时,我得到以下错误: import math pi = 3.1415 r = float(input("Enter the radius: ")) angle = float(input("Enter the angle: ")) x = r * math.cos(angle) y = r * math.sin(angle) print ('x =', x, 'y =', y) 有什么建议吗?您会得到错误,因为“pi”不是一个数字。如果您想让
import math
pi = 3.1415
r = float(input("Enter the radius: "))
angle = float(input("Enter the angle: "))
x = r * math.cos(angle)
y = r * math.sin(angle)
print ('x =', x, 'y =', y)
有什么建议吗?您会得到错误,因为
“pi”
不是一个数字。如果您想让它识别该字符串,您需要在尝试将其转换为浮点之前手动执行该操作
ValueError: could not convert string to float: 'pi'
然后,在主代码中,只需使用以下命令:
def get_number(what):
# Get value from user; remove any leading/trailing whitespace
val = input('Enter the {}:'.format(what)).strip()
if val.lower() == 'pi': # case insensitive check for "pi"
return math.pi
try: # try converting it to a float
return float(val)
except ValueError: # the user entered some crap that can't be converted
return 0
并且请去掉
pi=3.1415
-当您需要pi时,您可以使用更精确的pi和方法。此代码在python 2中运行良好,但在python 2和python 3之间更改了输入
函数,符合以下要求:
- Python2中的
现在在Python3中被称为raw_input
input
- python 2中的
相当于python 3中的input(x)
eval(input(x))
eval
是不安全和不直观的,当然不应该是用户输入的默认值,如果这是您真正想要的,那么仍然很容易做到
以您的代码示例为例,您可以通过替换
r = get_number('radius')
angle = get_number('angle')
与
但您不希望在实际代码中这样做。相反,您可能希望使用此问题中建议的解决方案之一:。是的,他根据异常输入了“pi”。这是非常简单的代码。试着理解它的每一行,查找任何你不懂的东西。虽然这可以解决眼前的问题,但我不认为它非常有用,因为它不会处理像“2*pi”这样的事情。
r = float(input("Enter the radius: "))
angle = float(input("Enter the angle: "))
r = float(eval(input("Enter the radius: ")))
angle = float(eval(input("Enter the angle: ")))