Вопрос

I am trying to subtract numbers from a list that the user enters. For example, I have this for addition which works the way I want it to:

print("\nAddition")
n = int(input('How many numbers are you adding?: '))
L = []
for i in range(n):
    L.append(int(input("Enter a number: ")))
    answer = sum(L)
    print(answer)

How do I go about doing the same for subtraction?

Это было полезно?

Решение

For subtraction you could loop yourself and subtract:

result = L[0]
for num in L[1:]:
    result -= num

This presumes that you want to start with the first number and subtract all the other numbers from that first value.

You could still use sum() but then you'd have to map() all but the first number to negative:

from operator import neg

result = sum(map(neg, L[1:]), L[0])

The operator.neg() function negates numbers, and we make use of the second argument to sum() to provide a start value.

Demo:

>>> from operator import neg
>>> L = [42, 10, 3, 8]
>>> sum(map(neg, L[1:]), L[0])
21
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top