0

I am working on a code with trying to find the sum of the numbers:

-817930511,
1771717028,
4662131,
-1463421688,
1687088745

I have put them in a separate file as I should but I am confused as to why my code is not working.

#finding the sum
def main():
filename = input("Please enter your file name: ")
openthefile=open(filename,'r')
sum_number=0
for line in openthefile:
    for the number in line.split(","):
        sum_number=sum_number+float(numbers.strip()
print('The sum of your numbers is', sum_number)


main()

I keep getting the syntax error appearing on the 7th line of code I have changed it around some there too but can't seem to see what is wrong.

4
  • 1
    it should be number.strip() and for number in ... Commented Oct 27, 2017 at 6:41
  • I have changed what you suggest but it now says invalid syntax still highlighting the number in the 7ht line. Commented Oct 27, 2017 at 6:50
  • First of all the indentation is wrong, at least in the example you have provided. As @VanPeer mentioned for the number will throw an error. That's wrong syntax. Also calling numbers.strip() will throw NameError. You don't have any variable with the name numbers in your code. Commented Oct 27, 2017 at 6:50
  • 1
    And you missed a ) after number.strip() that clauses the cast to float. Commented Oct 27, 2017 at 7:03

2 Answers 2

2

Simplified using sum and - more importantly - strip:

def main():
    # ...
    s = sum(float(l.strip(', \n')) for l in openthefile)
    print('The sum of your numbers is', s)

This strips away the comma ',', spaces ' ' (just to be safe), and the linebreak '\n' at the end of each line before turning the remainder into a float.

Sign up to request clarification or add additional context in comments.

Comments

1

Input file

-817930511, 1771717028, 4662131, -1463421688, 1687088745,

Code

#finding the sum
def main():
    filename = input("Please enter your file name: ")
    openthefile=open(filename,'r')
    b=0
    for line in openthefile:
        a = ([float(x) for x in line.split(',') if x])
        b = sum(a)
    print("The sum of your numbers is", b)

main()

Output

The sum of your numbers is 1182115705.0

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.