Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 21 Online
OpenStudy (anonymous):

Hi, I'm following prof.Guttag's book, and i've gotten stuck at a simple exercise. I have to add the decimal numbers in a string.But i keep getting an error, either "cannot convert string to float" when i try to exactly as the requirement.Or that the comma , is an "invalid literal" when i change everything to be an int. What am i missing? Thank you in advance for you're help ! :)

OpenStudy (mathmate):

It would help better if you could post an image of the question, and show what exactly you did.

OpenStudy (rsmith6559):

Both the float() and int() functions convert a number written as a string to a number. Your mention of commas makes me wonder if you have a list of strings that need to be converted one at a time.

OpenStudy (anonymous):

Hi, Here is my 'code'. :). s = '1.23,2.4,3.123' total = 0.0 for c in s: total += float(c) print total

OpenStudy (mathmate):

as @rsmith6559 commented, strings representing single numbers will be converted automatically, but strings containing comma delimited values will not be converted automatically to an array. For what you need to do, you can define s as a list by s= [1.23,2.4,3.123] and the rest of the code should work.

OpenStudy (mathmate):

... except print total should read print(total)

OpenStudy (anonymous):

Defining s as a list does work, however is there anyway for it to work keeping s='1.23,2.4,3.123' ? Just curious, seems strange because the book explicitly says to define s as such

OpenStudy (mathmate):

ok, that was an exercise to convert a string containing comma-delimited numbers. So your program will require some string manipulations to do that. You will need to read it as a string and use the string functions (look up "split", for example) to make the list indirectly.

OpenStudy (anonymous):

I had some trouble on this, and am quickly realizing that the book isn't going to always give you all the tools you need to solve the finger exercises right away. This is what I came up with s = str(raw_input('Enter a string of decimals seperated by commas: ')) total = 0 for i in s.split(','): total = total + float(i) print 'Sum of digits =', total

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!