Skip to main content
 首页 » 编程设计

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

2025年05月04日15zhenyulu

我的目标是创建一个将度数转换为弧度的程序。公式是 (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