karioki
karioki

Reputation: 3

Finding The Sum in Python

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.

Upvotes: 0

Views: 86

Answers (2)

user2390182
user2390182

Reputation: 73498

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.

Upvotes: 2

Van Peer
Van Peer

Reputation: 2167

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

Upvotes: 1

Related Questions