-2

how come

int('1') != int()
True

I converted the string to int but the expression shows it is True.

Sorry.

Can Anyone tell me how to achieve this "If this is not an int then True"

G-Ox7cd
  • 51
  • 1
  • 4
  • 9

8 Answers8

3

You are attempting to check whether a number is equal to its type (and not actually doing that). It is not. Numbers are numbers, and types are types. To check the type, use type() or isinstance():

>>> x = type(int('1'))
>>> y = isinstance(int('1'), int)
>>> x
<class 'int'>
>>> x == int
True
>>> y
True
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
3

As many people mention it above, int() returns a 0. In order to determine whether a variable is an integer or not, you must usetype. so you can check whether a variable is an int it by calling

type(int('1')) == int

which will return true. If you are looking to check whether a variable is not int, just negate the code above as such:

type(int('1')) != int
Jin
  • 92
  • 3
2

Because int() is:

>>> int()
0

And of course, 1 is never equal to 0.

>>> type(int('1')) == int
True
>>> isinstance(int('1'), int)
True
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

int() evaluates to 0

your code is basically int('1') == 0

This is False

Thmei Esi
  • 434
  • 2
  • 9
0
>>> int()
0
>>> int('1')
1

int() returns 0, so the expression evaluates to 1 != 0 which is True. If you meant something more like:

>>> isinstance(int('1'), int)
True
>>> type(int('1')) == type(int())
True
rassar
  • 5,412
  • 3
  • 25
  • 41
0

Default int() is 0

To check your value you can use You can use type: type(int('1'))

Shubham Namdeo
  • 1,845
  • 2
  • 24
  • 40
0
isinstance(int('1'), int)

or

type(int('1')) == type(int())

Both return true.

ref this thread How to check if type of a variable is string?, I believe it's same thing.

Community
  • 1
  • 1
Jacob
  • 561
  • 4
  • 9
0

From the result your got lets look at it this way.

The function int() does casts on values entered, in your case '1'. So it simply says:

cast '1' to an integer --> int('1') which gives 1

cast 'nothing' --> int() which gives '0'

So when you ask the question int('1') != int() which translates to:

is the value of the cast int('1') different from the value of the cast int()

then the answer should rightfully be true which is what you have. But if you had asked:

are their values the same, i.e. int('1') == int()

then the answer would have been false

George Udosen
  • 906
  • 1
  • 13
  • 28