Frage

I'm trying to subtract the values in an array with 10 values that the user inputs. So far I can't find how to do that. This is what I have...

g = 0
q = []

for s in range(9):    
    while g < 10:
        n = input()
        q.append(int(n))
        g = g+1

add = sum(Q)

sub =
War es hilfreich?

Lösung

There are more succinct ways to do this; I've opted instead for readability:

# get our initial input:
n = input()
result = int(n)

# subtract the rest of the user's inputs:
for x in range(9):
    n = input()
    result -= int(n)

# ... do something with the result ...

Andere Tipps

You don't need to assign all of those to individual variables. At each iteration of the loop, you could just append the newly input value to the array:

q = []
g = 0
while g < 10:
    n = input()
    q.append(int(n))
    g = g + 1

At the end of this loop, q will contain the 10 values that the user entered.

It's not clear to me what needs to be subtracted from what, but that might get you a little closer to where you need to be.

Be pythonic

a = [int(input()) for x in range(10)]

Or for python 2.X

a = [int(raw_input()) for x in xrange(10)]

This gives you a list containing 10 integers.

Then you can q = map(lambda x: x-sum(a), q), which subtracts the sum of user inputs

Just use python API

li = []
for x in xrage(10):
    li.append(input())
result = reduce(lambda x, y: x - y, li)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top