0

I have an exercise:

Write code that asks the user for integers, stops loop when 0 is given. Lastly, adds all the numbers given and prints them.

So far I manage this:

a = None
b = 0
while a != 0:
    a = int(input("Enter a number: "))
    b = b + a
print("The total sum of the numbers are {}".format(b))

However, the code needs to check the input and give a message incase it is not an integer.

Found that out while searching online but for the life of me I cannot combine the two tasks.

while True:
    inp = input("Input integer: ")
    try:
        num = int(inp)
    except ValueError:
        print('was not an integer')
        continue
    else:
        total_sum = total_sum + num
        print(total_sum)
        break

I suspect you need an if somewhere but cannot work it out.

miken32
  • 42,008
  • 16
  • 111
  • 154
  • What do you mean by "combine"? The second code would basically replace the first code. What parts of the first code do you feel are missing in the second code? – mkrieger1 Apr 18 '22 at 22:15
  • In the `else` clause check to see if the value of `num` is zero — meaning it's time to stop the loop by printing the sum and `break` — otherwise just add it to the running total. – martineau Apr 18 '22 at 22:51

3 Answers3

1

Based on your attempt, you can merge these two tasks like:

a = None 
b = 0 
while a != 0: 
    a = input("Enter a number: ") 
    try: 
        a = int(a) 
    except ValueError: 
        print('was not an integer') 
        continue 
    else: 
        b = b + a  
print("The total sum of the numbers are {}".format(b))
Renato Miotto
  • 251
  • 2
  • 4
1

If you want to use an If-Statement, you don't need the else: If the number is not 0 it will just start again until it's 0 sometime.

total_sum = 0
while True:
    inp = input("Input integer: ")
    try:
        num = int(inp)
    except ValueError:
        print('was not an integer')
        continue
    total_sum = total_sum + num
    if num == 0:
        print(total_sum)
        break
0

Since input's return is a string one can use isnumeric no see if the given value is a number or not.

If so, one can convert the string to float and check if the given float is integer using, is_integer.

a = None 
b = 0 
while a != 0: 
    a = input("Enter a number: ") 
    if a.isnumeric():
        a = float(a)
        if a.is_integer():
            b += a
        else:
            print("Number is not an integer")
    else:
        print("Given value is not a number")
        
print("The total sum of the numbers are {}".format(b))
MSH
  • 1,743
  • 2
  • 14
  • 22