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"
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"
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
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
Because int()
is:
>>> int()
0
And of course, 1
is never equal to 0
.
>>> type(int('1')) == int
True
>>> isinstance(int('1'), int)
True
>>> 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
Default int()
is 0
To check your value you can use You can use type:
type(int('1'))
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.
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