I am quite new to Python so I am having trouble doing my assignment. I need to create a program that adds an unspecified amount of positive numbers entered by the user, and the program will stop if the user entered a zero or a negative number. Then it prints out the total. I think the problem with my code is that it doesn’t loop. Please help me with this, thank you.
def again():
c = 0
a = int(input("a"))
if a >= 1:
b = int(input("b"))
while a and b >= 1:
if b >= 1:
c += (a + b)
print("Result",c)
again()
break
if a >= 0 and b >= 0:
break
again()
Advertisement
Answer
Your logic and syntax has some errors and it’s hard to follow. Hope this code snippet below can help you:
def again():
# ask user to input a number:
total = 0 # to sum up all entering numbers...
while True:
x = int(input('Please enter a positive number, or zero/negative to "Exit": '))
if x > 0: total += x
elif x <= 0: # see negative number
print(f' total: {total} ')
break
again()
running (and input number)
Please enter a positive number, or negative to "Exit": 1 Please enter a positive number, or negative to "Exit": 2 Please enter a positive number, or negative to "Exit": 3 Please enter a positive number, or negative to "Exit": 4 Please enter a positive number, or negative to "Exit": 5 Please enter a positive number, or negative to "Exit": -1 total: 15