Search code examples
stringpython-3.xint

How to check if the input string is an integer


if input()==int():
    print('mission successful!')
else:
    print('mission failed!')

for above code the problem is, that it never results in mission successful even though my input is integer.

I have just started learning python.


Solution

  • To check if the input string is numeric, you can use this:

    s = input()
    if s.isnumeric() or (s.startswith('-') and s[1:].isdigit()):
        print('mission successful!')
    else:
        print('mission failed!')
    

    In Python, checking if a string equals a number will always return False. In order to compare strings and numbers, it helps to either convert the string to a number or the number to a string first. For example:

    >>> "1" == 1
    False
    >>> int("1") == 1
    True
    

    or

    >>> 1 == "1"
    False
    >>> str(1) == "1"
    True
    

    If a string can not be converted to a number with int, a ValueError will be thrown. You can catch it like this:

    try:
        int("asdf")
    except ValueError:
        print("asdf is not an integer")