Python help return

I got the code to work, I’m just having problems with a reset or restart command at the bottom to repeat the code over. Any ideas?

while True:
n=int(input("How many numbers would you like to add?: "))
b=[]
for i in range(0,n):
a=int(input("Please enter a number: "))
b.append(a)
sum1=0
sum2=0
sum3=0
for j in b:
if(j>0):
sum1=sum1+j
if(j<0):
sum2=sum2+j
sum3=sum3+j
print(“Sum of all the positive numbers:”,sum1)
print(“Sum of all the negative numbers:”,sum2)
print(“Sum of all the numbers:”,sum3)

answer=(str(input("Do you want to reset yes Y or no N ?")))
if answer=='N':
    break

elif answer=="Y":
    return 1

You don’t need the elif statement. Just check to see

if answer in ("no", "NO", "No", "N", "n"): # whoo, i love getting fancy
    break

and then anything else will not break the while True: loop and go back to the top

This is probably your issue. Unless theres more to the code shown, you cannot return something if its not within a function, and chances are you’re getting a stynax error to that effect.

Youre also not doing anything with that return, so im not sure of its purpose in general, unless theres more to the code shown.

Not really related to the restart issue, id double check that the sum3 variable is actually doing what you want it to. Testing it did not provide the result i expected it to return.

Even more concise:

if answer.lower() in ("no", "n"):
    break

And yea, OP - in that case, the continue keyword is probably what you were meaning instead of return.

break says “stop here and exit the loop”, continue says “stop here and restart the loop”.

That being said, having the statement continue at the very end of a while loop is a “no-op”, because the while loop would have done that automatically anyway. Hence why it can probably just be deleted without issue.

3 Likes