netbyte
netbyte

Reputation: 11

Having trouble with string to float in python

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!

Upvotes: 1

Views: 604

Answers (2)

Kristian Glass
Kristian Glass

Reputation: 38540

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()

Upvotes: 2

DSM
DSM

Reputation: 353569

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

Upvotes: 8

Related Questions