# Tutorial by Examples

## Greater than or less than

x &gt; y x &lt; 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 &gt; 4 # True 12 &lt; 4 # False 1 &lt; 4 # True For strings they will compare lexicographical...

## Not equal to

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

## Equal To

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' == ...

## Chain Comparisons

You can compare multiple items with multiple comparison operators with chain comparison. For example x &gt; y &gt; z is just a short form of: x &gt; y and y &gt; 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 ...

## Comparison by `is` vs `==`

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 ...

## Comparing Objects

In order to compare the equality of custom classes, you can override == and != by defining __eq__ and __ne__ methods. You can also override __lt__ (&lt;), __le__ (&lt;=), __gt__ (&gt;), and __ge__ (&gt;). Note that you only need to override two comparison methods, and Python can handle the rest (== ...

## Common Gotcha: Python does not enforce typing

In many other languages, if you run the following (Java example) if(&quot;asgdsrf&quot; == 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