1
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.

2
  • 1
    It's important to know that input() will not give you an integer, but a string, even if you input a number. Commented Jul 24, 2017 at 11:42
  • 2
    Possible duplicate of How to check if string input is a number? Commented Jul 24, 2017 at 13:44

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

1 Comment

First method fails for negative ints or floats

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.