1

I want to make a program where I need to check the input of the user so, the question is How do I check the input value, if it`s a string or an integer?

Here's some experimental code that didn't work:

a = 10

print(type(a))


if (a==10):
    print("aaaaa")
else:
    if(type(a)== "<class 'int'>"):
        print("12345")
Paul Whipp
  • 16,028
  • 4
  • 42
  • 54
Lucas Fernandes
  • 29
  • 1
  • 2
  • 8
  • If you want to check user input, this isn't going to help. Whether the user types `123` or `abc`, you'll still get a string representing the sequence of characters they typed, not an int representing the numeric value of that character sequence interpreted as a base 10 representation of an integer. – user2357112 Oct 09 '19 at 06:30
  • Ok, so how do I check it ? – Lucas Fernandes Oct 09 '19 at 06:34
  • `type(a) == int` or `isinstance(a, int)`. If it is from input, meaning that `a` is a `str` and you want to check if `a` is an int-like `str`, you can do `a.isdigit()`. – Seaky Lone Oct 09 '19 at 06:36
  • 1
    @SeakyLone: `isdigit` is the wrong test. It tests for digit characters, not for strings that represent numbers. For example, `'-1'.isdigit()` is `False`. – user2357112 Oct 09 '19 at 06:42
  • @user2357112 you are right. Maybe I should say this `a[1:].isdigit() if a[0]=='-' else a.isdigit()`. But without further confirmation from the asker, the int checking is hard to give the precise answer. – Seaky Lone Oct 09 '19 at 06:46

2 Answers2

1

You can do it in the following way:

a = 10

if type(a) is int:
    print("Yes")
else:
    print("No")
MaleckiD
  • 11
  • 2
  • But not when `a` is user input, then `a` is always of type string. See how he asks that het wants to check user input. – Niels Henkens Oct 09 '19 at 06:46
  • Also `isinstance()` is usually prefered over `type()`. (Search SO for why that is, there are plenty well written answers explaining it. E.g. https://stackoverflow.com/a/1549854/6793245) – orangeInk Oct 09 '19 at 06:50
  • @orangeInk that's a good point. Thank you for this. – MaleckiD Oct 09 '19 at 06:57
  • @NielsHenkens you are absolutely right. It won't work with the user input. – MaleckiD Oct 09 '19 at 06:58
0

input() will always return string, i.e type(input()) will be str

from my understanding, you want to validate input before proceeding further , this is what you can do

foo = input()
if not foo.isdigit():
    raise ValueError("Enter a valid integer")
foo = int(foo)

this will not work for a negative number, for that you can check if foo startswith "-"

if foo.lstrip("-").isdigit():
    multiply_by = -1 if foo.startswith("-") else 1
    foo = multiply_by * int(foo.lstrip("-"))

and if you want to check type of variable

a = 10
if isinstace(a, int):
    pass
karansthr
  • 331
  • 2
  • 8
  • Using `isdigit` is a common mistake, but still wrong. For example, `'-1'.isdigit()` is `False`. `isdigit` is a test for digit characters, not for strings that represent numbers. – user2357112 Oct 09 '19 at 06:41