Comparison.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # # Comparisons
  4. #
  5. # Boolean values most often arise from comparison operators. Python includes a variety of operators that compare values. For example, `3` is larger than `1 + 1`.
  6. # In[1]:
  7. 3 > 1 + 1
  8. # The value `True` indicates that the comparison is valid; Python has confirmed this simple fact about the relationship between `3` and `1+1`. The full set of common comparison operators are listed below.
  9. #
  10. # | Comparison | Operator | True example | False Example |
  11. # |--------------------|----------|--------------|---------------|
  12. # | Less than | < | 2 < 3 | 2 < 2 |
  13. # | Greater than | > | 3>2 | 3>3 |
  14. # | Less than or equal | <= | 2 <= 2 | 3 <= 2 |
  15. # | Greater or equal | >= | 3 >= 3 | 2 >= 3 |
  16. # | Equal | == | 3 == 3 | 3 == 2 |
  17. # | Not equal | != | 3 != 2 | 2 != 2 |
  18. # An expression can contain multiple comparisons, and they all must hold in order for the whole expression to be `True`. For example, we can express that `1+1` is between `1` and `3` using the following expression.
  19. # In[2]:
  20. 1 < 1 + 1 < 3
  21. # The average of two numbers is always between the smaller number and the larger number. We express this relationship for the numbers `x` and `y` below. You can try different values of `x` and `y` to confirm this relationship.
  22. # In[3]:
  23. x = 12
  24. y = 5
  25. min(x, y) <= (x+y)/2 <= max(x, y)
  26. # Strings can also be compared, and their order is alphabetical. A shorter string is less than a longer string that begins with the shorter string.
  27. # In[4]:
  28. "Dog" > "Catastrophe" > "Cat"