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.
JavaScript
x
15
15
1
def again():
2
c = 0
3
a = int(input("a"))
4
if a >= 1:
5
b = int(input("b"))
6
while a and b >= 1:
7
if b >= 1:
8
c += (a + b)
9
print("Result",c)
10
again()
11
break
12
if a >= 0 and b >= 0:
13
break
14
again()
15
Advertisement
Answer
Your logic and syntax
has some errors and it’s hard to follow. Hope this code snippet below can help you:
JavaScript
1
18
18
1
def again():
2
# ask user to input a number:
3
total = 0 # to sum up all entering numbers...
4
5
6
while True:
7
x = int(input('Please enter a positive number, or zero/negative to "Exit": '))
8
9
if x > 0: total += x
10
11
elif x <= 0: # see negative number
12
print(f' total: {total} ')
13
break
14
15
16
17
again()
18
running (and input number)
JavaScript
1
9
1
Please enter a positive number, or negative to "Exit": 1
2
Please enter a positive number, or negative to "Exit": 2
3
Please enter a positive number, or negative to "Exit": 3
4
Please enter a positive number, or negative to "Exit": 4
5
Please enter a positive number, or negative to "Exit": 5
6
Please enter a positive number, or negative to "Exit": -1
7
total: 15
8
9