Operator

From CS 61A Wiki
Jump to: navigation, search

This is a list of Python operators.

Arithmetic operators

  • addition (+)
  • subtraction (-)
  • multiplication (*)
  • floating point division (/)
  • integer division (//) – rounds towards negative infinity
  • modulus (%) – remainder

Examples:

>>> 1 + 2
3
>>> 5 - 2
3
>>> 2 * 3
6
>>> 3 / 3
1.0
>>> 3 / 2
1.5
>>> 3 // 2
1
>>> 3 % 2
1

Comparison operators

The following operators work on numbers, sequences, and other data structures.

  • equal (==)
  • not equal (!=)
  • greater than (>)
  • less than (<)
  • greater than or equal (>=)
  • less than or equal (<=)

Examples:

>>> 2 == 3
False
>>> 3 == 3
True
>>> 2 < 3
True
>>> [1, 2] == [1, 2]
True
>>> "a" < "b"
True

Logical operators

  • not – negates the boolean expression
  • and – returns true if all the operands are true
  • or – returns true if one of the operands is true

Examples:

>>> 1 < 2 and 3 < 4
True
>>> 1 < 2 or 3 > 4
True
>>> not 1 < 2
False
>>> not (1 < 2)
False

and and or are short-circuiting, which means that evaluation stops as soon as the outcome is determined

  • and stops if there is a false value and returns false
  • or stops if there is a true value and returns true

The order of operations for boolean operators is not, and, or. For example, the expression False or True and not False or False can be rewritten as False or (True and (not False)) or False, which evaluates to True.

If not used in a boolean context, and returns the first false value or the last value if all are true; or returns the first true value or the last value if all are false. Examples:

>>> 0 and 1 # 0 is first false value
0
>>> 1 and 2 # both are true
2
>>> None or 2 # 2 is first true value
2
>>> None or 0 # both are false
0

Membership operators

in and not in work on sequences, dictionaries, and sets. See the article for the data structure for usage.

Identity operators

Main article: Identity vs. equality#Identity (is, is not)

is and is not check if the operands point to the same object in memory.

Sources