Python 3.2.3 值错误 : could not convert string to float

标签 python

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/

相关文章:

python正则表达式在<a>元素处拆分字符串并提取链接+文本

python - 如何让 MagicMock 表现得像一个字典?

python - xml 从 python 字典中转义

python - 在 Django 中使用 ThreadPoolExecutor 时出现数据库 "is being accessed by other users"错误

python - 官方文档中的 pyspark 线性回归示例 - 结果不好?

python - 在 Django 中国际化图像

python - Tensorflow安装错误: No module named _pywarp_tensorflow

python - 如果包含子字符串,则同时替换多个字符串

python - OSX 如何在使用 C++ 扩展 python 时调试 malloc 错误?

python - 如何在 xlwt 中编写具有多列的单元格?