简体   繁体   中英

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 (eg 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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM