В вашем коде есть несколько ошибок.Мое основное правило - сделать каждый шаг своей функцией.Вы можете сделать все это в одной функции, но потом будет сложно добавлять вещи.
# Opens the file and appends each number to a list, returns list
def open_file(filename):
output = []
f = open(filename, "r")
for line in f:
output.append(int(line.strip()))
return output
# Takes an input like a list and squared each number, returns the list
def square_number(input):
return [num*num for num in input]
# sums the list
def sum_numbers(input):
return sum(input)
# the start, function calls within function calls
the_sum = sum_numbers(square_number(open_file('4numsin.txt')))
#check the result
print(the_sum)
>> 204
Посмотрите, насколько эффективнее иметь отдельные методы / функции?
# look at other things
print(open_file('4numsin.txt'))
>> [0, 1, 2, 3, 4, 5, 6, 7, 8]
print(sum_numbers(open_file('4numsin.txt')))
>> 36