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 或任何带有 pi 的内容作为角度提示的答案时,出现此错误:
ValueError: could not convert string to float: 'pi'
有什么建议吗?
最佳答案
您收到错误是因为 "pi"
不是数字。如果您希望它识别该字符串,您需要在尝试将其转换为 float 之前手动执行此操作。
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
然后,在您的主代码中,只需使用:
r = get_number('radius')
angle = get_number('angle')
请去掉pi = 3.1415
- 当你需要pi时,你可以使用math.pi
这是更准确和可行的方法。
关于Python 3.2.3 值错误 : could not convert string to float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12227653/