I am making an AJAX call and passing variable pub
in it which could be 1
or 0
.
As a beginner I want to be double sure of the variable type that is coming in. I am aware I can easily convert to int()
and the problem is actually not with AJAX result but it led to this question.
My code:
if pub == 1 or pub == '1':
#execute funcA()
But the above is not so pythonic for me so I tried:
if pub in [1,'1']:
#execute funcA()
Which of the above code is better in terms of:
The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=
Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.
Use the == operator to test if two variables are equal.
The main difference between the 1 and 1. is in their type and type of the result of any equation that include float number in python will be float. That include addition subtraction multiplication exponents and even the integer division as if one operand is float answer will be of type float.
Python - cmp() function cmp() is an in-built function in Python, it is used to compare two objects and returns value according to the given values. It does not return 'true' or 'false' instead of 'true' / 'false', it returns negative, zero or positive value based on the given input.
This code is better
if pub in [1,'1']:
#execute funcA()
because it's slightly faster but mainly because it is not redundant. The variable pub
appears only once there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With