So the exercise is to get input from users until they enter a negative number and then calculate the sum of numbers before the negative one. (using while loop).
while True:
a = 0
summ = 0
while a >= 0:
a = int(input("enter a number: "))
summ = summ a
if a < 0:
print(summ)
This was the code that I wrote for this exercise, but the problem is that it calculates the negative number too. I'm pretty new to python, and this is one of the python exercises that I should do to learn more about algorithms.
CodePudding user response:
You need use IF statements to check negative values
summ = 0
while True:
a = int(input("enter a number: "))
if a < 0:
break
summ = summ a
print(summ)
CodePudding user response:
state = True
summ = 0
while state:
a = int(input("enter a number: "))
if a >= 0:
summ = summ a
else:
state = False
print(summ)
CodePudding user response:
Use the continue statement, which skips a given iteration
while True:
a = 0
summ = 0
while a >= 0:
a = int(input("enter a number: "))
summ = summ a
if a < 0:
continue
print(summ)
break