0

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)
5
  • You assign to "number" in each loop iteration but you only use last value. Commented Dec 15, 2019 at 2:18
  • 1
    you should use ntotal = ntotal - nn and at the end use print(ntotal) Commented Dec 15, 2019 at 2:19
  • Your code seems to do more than what you described and it's confusing. What is ntotal supposed to be? Why print('Please enter n: ')? Also k is unused. Please make a minimal reproducible example. Commented Dec 15, 2019 at 2:22
  • Also are you not allowed to use range? BTW welcome to Stack Overflow! Check out the tour. Commented Dec 15, 2019 at 2:24
  • 1
    Oh I just realized ntotal == sum(range(n+1)) Commented Dec 15, 2019 at 2:29

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.