0

So, basically, as the title states "I'm trying to test if the input a is an integer and if not loop back to the top of the loop" when I do it the program only prints(a is not a number start over) even when a is a number and b is not or if a and b are numbers.

def multiply():
    while True:
        a = input("enter something: ", )
        b = input("enter something: ", )
        if(a != int(a)):
            print("a was not a number start over")
            multiply()
        elif(b != int(b)):
            print("b was not a number start over")
            multiply()
        else:
            sum = a * b
            print(sum)
            break


multiply()
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Tomerikoo Mar 17 '21 at 20:24
  • `a != int(a)` is always true because `a` is a string... – Tomerikoo Mar 17 '21 at 20:25
  • @Tomerikoo, Thanks. I actually didn't know that I had it as int(input()) but I wanted it to check if the user did a string or a number but if not I wanted it to loop back in doing so I broke it thanks let me try and fix that. –  Mar 17 '21 at 20:41
  • Okay i see what it's a string –  Mar 17 '21 at 20:50

1 Answers1

0

The input function always returns a string.

>>> x = input("enter a number: ")
enter a number: 123
>>> print(x)
123
>>> type(x)
str

You need to cast the user's input as an int first, and handle the case when the user's input is not a valid int value:

def get_integer_input(message):
    value = input(message)
    try:
        return int(value)
    except ValueError:
        print("Invalid input! You must enter a valid integer.")
        return None

# Invalid input "foobar"
>>> get_integer_input("Enter an integer: ")
Enter an integer: foobar
Invalid input! You must enter a valid integer.

# Valid input 101
>>> get_integer_input("Enter an integer: ")
Enter an integer: 101
101
damon
  • 14,485
  • 14
  • 56
  • 75
  • This was a program to start kids out in programming so I was hoping to make a multiplication program but somewhat kind of simpler. Something I can understand and explain to kids that don't confuse them. I'm sorry I should have said that part. –  Mar 17 '21 at 20:38
  • I had a working version but i wanted it all in one function so I broke it trying to create that –  Mar 17 '21 at 20:39
  • def multiply(): while True: try: a = int(input("enter something: ", )) b = int(input("enter something: ", )) sum = a * b print(sum) break except ValueError: print("you have to enter a number sorry you have to start over") multiply() break multiply() –  Mar 17 '21 at 21:05
  • 1
    This is what i was going for but it works now with your idea so thanks –  Mar 17 '21 at 21:06