Tutorial by Examples

x > y x < y These operators compare two types of values, they're the less than and greater than operators. For numbers this simply compares the numerical values to see which is larger: 12 > 4 # True 12 < 4 # False 1 < 4 # True For strings they will compare lexicographical...
x != y This returns True if x and y are not equal and otherwise returns False. 12 != 1 # True 12 != '12' # True '12' != '12' # False
x == y This expression evaluates if x and y are the same value and returns the result as a boolean value. Generally both type and value need to match, so the int 12 is not the same as the string '12'. 12 == 12 # True 12 == 1 # False '12' == '12' # True 'spam' == 'spam' # True 'spam' == ...
You can compare multiple items with multiple comparison operators with chain comparison. For example x > y > z is just a short form of: x > y and y > z This will evaluate to True only if both comparisons are True. The general form is a OP b OP c OP d ... Where OP represents ...
A common pitfall is confusing the equality comparison operators is and ==. a == b compares the value of a and b. a is b will compare the identities of a and b. To illustrate: a = 'Python is fun!' b = 'Python is fun!' a == b # returns True a is b # returns False a = [1, 2, 3, 4, 5] b = a ...
In order to compare the equality of custom classes, you can override == and != by defining __eq__ and __ne__ methods. You can also override __lt__ (<), __le__ (<=), __gt__ (>), and __ge__ (>). Note that you only need to override two comparison methods, and Python can handle the rest (== ...
In many other languages, if you run the following (Java example) if("asgdsrf" == 0) { //do stuff } ... you'll get an error. You can't just go comparing strings to integers like that. In Python, this is a perfectly legal statement - it'll just resolve to False. A common gotcha ...

Page 1 of 1