1

My goal is to create a program that will convert degrees to radians. The formula is (degrees * 3.14) / 180. But python keeps giving me this error:

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'

From this code:

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

main()

EDIT: Thank you all for the help!

mskfisher
  • 3,291
  • 4
  • 35
  • 48
netbyte
  • 11
  • 3

2 Answers2

8
float(degrees) 

doesn't do anything. Or, rather, it makes a float from the string input degrees, but doesn't put it anywhere, so degrees stays a string. That's what the TypeError is saying: you're asking it to multiply a string by the number 3.14.

degrees = float(degrees)

would do it.

Incidentally, there are already functions to convert between degrees and radians in the math module:

>>> from math import degrees, radians, pi
>>> radians(45)
0.7853981633974483
>>> degrees(radians(45))
45.0
>>> degrees(pi/2)
90.0
DSM
  • 342,061
  • 65
  • 592
  • 494
  • 1
    I would just add that Strings are immutable in python thus all operations on them create a new object, never modify the original. – Zenon Apr 01 '12 at 01:29
  • Thanks!! Yeah, I know, but my teacher wants me to make a function for that myself. – netbyte Apr 01 '12 at 01:33
2

float() doesn't modify its argument, it returns it as a float. I suspect what you want is (also adding standard __name__ convention out of habit):

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

if __name__ == '__main__':
    main()
Kristian Glass
  • 37,325
  • 7
  • 45
  • 73