Home > Enterprise >  Loop and check if integer
Loop and check if integer

Time:04-19

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.

CodePudding user response:

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))

CodePudding user response:

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

CodePudding user response:

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))
  • Related