Operators (Python)

(Redirected from Operator)

In computer programming, operators are built-in functions similar to mathematical operations. This article focuses primarily on numerical operators and relational operators. For other types and some special cases, see String operations, Boolean operations and Sequence operations.

Numerical Operators

  • x + y returns the sum of x and y.
  • x - y returns the difference of x and y.
  • x*y returns the product of x and y.
  • x/y returns the quotient of x and y. The result will always be a float.
  • x//y returns the quotient of x and y rounded down to the nearest integer. This is also known as integer division. The result will still be a float if one of the inputs was.
  • x%y is the modulo operation, and returns the remainder when x is divided by y.
  • -x returns the negation of x.
  • abs(x) returns the absolute value of x.
  • x**y and pow(x,y) both return $x^y$. As is common for programming languages, Python defines 0**0 to be 1, despite the fact that $0^0$ is undefined in many mathematical contexts.

For the operators that take more than one argument, if either of the arguments are floats the output will always be a float (rather than an integer) unless otherwise noted.

Relational Operators

Relational operators, also simply called comparisons, are operators that return booleans.

  • x < y returns True iff x is strictly less than y.
  • x > y returns True iff x is strictly greater than y.
  • x <= y returns True iff x is less than or equal to y.
  • x >= y returns True iff x is greater than or equal to y.
  • x == y returns True iff x is equal to y.
  • x != y returns True iff x is not equal to y.

Notes:

  1. In Python, = is not a relational operator, it's actually the assignment operator. == is used for equality testing.
  2. When comparing strings to each other Python uses lexicographic order, so one string will be less than another if it would appear earlier in a dictionary.
  3. It's bad practice to rely on equality testing of floating point numbers. See the related article for an explanation.

Precedence Rules

Python understands and adheres to the standard precedence rules. In particular, operators will be applied in the following order:

  1. Terms in parentheses
  2. Exponentiation
  3. Negation
  4. Multiplication and division
  5. Addition and subtraction
  6. Comparisons
  7. Boolean operations (e.g. and, or, and not)

Operators of the same precedence level are applied from left to right. For more clarity or if you need to override these rules you can enclose subexpressions in parentheses.

See Also

Python 3.2 Documentation