In: Computer Science
Write a python program that asks the user to enter a string containing numbers separated by commas, e.g., s = '1.23,2.4,3.123', Your program should then calculate and print the sum of the numbers entered. Hint: you need to iterate over the string searching for the commas, i.e. their index. The first number is obtained by slicing between the start of the string and the index of the first comma. The second number is between the last comma and the next one, and so on. For this program do not use the standard string functions.
#Program to add numbers in a string without using standard string functions
s=input("s= ") #taking input from the user
lastpos=0 #this will store the index of last comma found
sum=0 #our total sum will be stored in this variable
for i in range(len(s)): #this loop will iterate over the
string
if s[i]==",": #this condition will check if we found the
comma
sum+=float(s[lastpos:i]) #slicing the number found between last
comma and the next comma found
lastpos=i+1 #updating the position of last comma found
print("sum= ",sum) #Printing the sum of the numbers
#NOTE: In this program do not forget to put comma at the end while taking input as shown in example given in #question, otherwise answer will be wrong
#In this program we have converted the number to float type insteed of integer because we cannot take float value #as integer but we can take integer value as float in python
Output and coding screen:
some more outputs are: