My assignment is:
"Write a function sumOfDigits that has one parameter of type string. The function should return the sum of the digits in the string. Do not treat multiple digit string as one number – “2014” should be treated as 4 different digits of 2, 0, 1, 4. The function should return 17 for the string “Today’s date is 09/01/2014”. You can assume the parameter is a string. No need to do any type validation."
Here's what I've got so far (with appropriate indentation):
def sumOfDigits (string1: str):
summation=0
for i in string1:
summation=summation + int (i)
return (summation)
print (sumOfDigits ('543tf'))
I get the following error:
"Traceback (most recent call last):
File "C:\Users\Andrew\Desktop\lab3.py", line 45, in <module>
print (sumOfDigits ('543tf'))
File "C:\Users\Andrew\Desktop\lab3.py", line 42, in sumOfDigits
summation=summation + int (i)
ValueError: invalid literal for int() with base 10: 't'"
How do I solve this? Is it doing this because of the difficulties associated with adding an int and string/char?