-5

I am trying to write a program that will add together a series of numbers that the user inputs until the user types 0 which will then display the total of all the inputted numbers. this is what i have got and im struggling to fix it

print ("Keep inputting numbers above 0 and each one will be added together consecutively. enter a and the total will be displayed on the screen. have fun")

number = input("Input a number")

sum1 = 0

while number >= 1:

    sum1 = sum1 + number

if number <= 0:
    print (sum1) 
  • You haven't explained what's broken. – Ignacio Vazquez-Abrams Aug 30 '17 at 11:30
  • Please explain what is wrong. What output are you expecting? What actually output/error are you getting? – Christian Dean Aug 30 '17 at 11:30
  • Please explain the problem. What is happening? What is not working? What have you tried to do? The question should have a clear explanation of the problem. But as to the actual issue, read your code through and think on every line what happens, when the user is asked for something etc. You should see the problem. Or get a debugger and run it line by line. – Sami Kuhmonen Aug 30 '17 at 11:31
  • Traceback (most recent call last): File "D:/Python/NEA practice/sum.py", line 7, in while number >= 1: TypeError: unorderable types: str() >= int() >>> is the output im getting – Jack Clemmey Aug 30 '17 at 11:51
  • i have managed to fix it now thanks for the help – Jack Clemmey Aug 30 '17 at 11:53

2 Answers2

1

Here is a more robust way to input the number. It check if it can be added. Moreover I added the positive and negative number.

# -*-coding:Utf-8 -*

print ("Keep inputting numbers different than 0 and each one will be added together consecutively.") 
print ("Enter a and the total will be displayed on the screen. Have fun.")

sum = 0
x = ""

while type(x) == str:
        try:
                x = int(input("Value : "))
                if x == 0:
                        break
                sum += x
                x = ""
        except:
                x = ""
                print ("Please enter a number !")

print ("Result : ", sum)
Mathieu
  • 5,410
  • 6
  • 28
  • 55
0

If you're using Python 3, you will need to say number = int(input("Input a number")) since input returns a string. If you're using Python 2, input will work for numbers but has other problems, and the best practice is to say int(raw_input(...)). See How can I read inputs as integers? for details.

Since you want the user to repeatedly enter a number, you also need an input inside the while loop. Right now it only runs once.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89