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.

Alexander
  • 9,737
  • 4
  • 53
  • 59
A.Jha
  • 103
  • 1
  • 1
  • 5
  • 1
    It's important to know that `input()` will not give you an integer, but a string, even if you input a number. – Shinra tensei Jul 24 '17 at 11:42
  • 2
    Possible duplicate of [How to check if string input is a number?](https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number) – Chris_Rands Jul 24 '17 at 13:44

1 Answers1

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")
Alexander
  • 9,737
  • 4
  • 53
  • 59