python - 字符串在 python 中 float 时遇到问题

标签 python string error-handling floating-point

我的目标是创建一个将度数转换为弧度的程序。公式是 (degrees * 3.14)/180。但是 python 一直给我这个错误:

Traceback (most recent call last):
  File "2.py", line 6, in <module>
    main()
  File "2.py", line 4, in main
    degrees = (degrees * 3.14) / 180
TypeError: can't multiply sequence by non-int of type 'float'

来自这段代码:

def main():
    degrees = raw_input("Enter your degrees: ")
    float(degrees)
    degrees = (degrees * 3.14) / 180

main()

编辑:谢谢大家的帮助!

最佳答案

float(degrees) 

什么都不做。或者,更确切地说,它根据字符串输入 degrees 生成一个 float ,但不会将其放在任何地方,因此 degrees 仍然是一个字符串。这就是 TypeError 的意思:你要求它用数字 3.14 乘以一个字符串。

degrees = float(degrees)

会做的。

顺便说一句,数学模块中已经有度数和弧度之间的转换函数:

>>> from math import degrees, radians, pi
>>> radians(45)
0.7853981633974483
>>> degrees(radians(45))
45.0
>>> degrees(pi/2)
90.0

关于python - 字符串在 python 中 float 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9961175/

相关文章:

python - Pandas 数据帧导入和渲染不正确并导致 UnicodeDecodeError

r - downloadHandler在使用R Shiny下载图像时出错

java - 如何在多行输出 Java 中打印字符串

java - RX Java - 重试一些抛出异常的代码

error-handling - 谷歌分析 "There was an internal error"

python - 使用Python和OpenCV的图像拼接问题

python - 如何以编程方式在 virtualenv 中安装 Python 模块?

python - 如何替换特定子字符串后的部分字符串

C 返回字符串不正确

python - 如何从 python 中的字符串中删除 a\