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 ! :)
MIT 6.00 Intro Computer Science (OCW)
Stacey Warren - Expert brainly.com
Hey! We 've verified this expert answer for you, click below to unlock the details :)
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
I got my questions answered at brainly.com in under 10 minutes. Go to brainly.com now for free help!
It would help better if you could post an image of the question, and show what exactly you did.
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.
Here is my 'code'. :).
s = '1.23,2.4,3.123'
total = 0.0
for c in s:
total += float(c)
Not the answer you are looking for? Search for more explanations.
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
and the rest of the code should work.
... except print total should read print(total)
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
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.
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