Jorge Meza
Jorge Meza

Reputation: 9

Why doesn't the function in my while loop use the updated variable value

So I'm taking a beginner Python class and one of my questions is to write code that takes n number (e.g. 5) and asks the user to enter n-1 numbers in n and finds the missing number. I can't use anything more advanced than loops.

For some reason even though the value of nn gets updated ever time the loop runs the value of number only decreases by 1 every time the loop runs.

n = int(input('Please enter n: '))
ntotal = int(n*(n+1)/2)
print ('Please enter n: ')

print (ntotal)
i = 0
k = i
while i != n-1:
    nn = int(input('Please enter a number: '))
    number = ntotal - nn
    print (nn)
    i += 1

print (number)

Upvotes: 0

Views: 108

Answers (1)

furas
furas

Reputation: 143056

You have to change ntotal

    ntotal = total - number

or shorter

    ntotal -= number

and display ntotal at the end


n = int(input('Please enter n: '))
ntotal = int(n*(n+1)/2)

#print('ntotal:', ntotal)

i = 0
while i != n-1:
#for _ in range(n-1):
    number = int(input('Please enter a number: '))
    ntotal -= number
    #print('number:', number, 'ntotal:', ntotal)
    i += 1

print(ntotal)

Upvotes: 1

Related Questions