Difference between revisions of "Operators (Python)"
m (→Relational Operators)
Revision as of 08:03, 28 June 2011
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.
- 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 . As is common for programming languages, Python defines 0**0 to be 1 (in math it's usually undefined).
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, 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.
- In Python, = is not a relational operator, it's actually the assignment operator. == is used for equality testing.
- When comparing strings to each other Python uses lexicographic order, so a string will be "less than" another if it would appear earlier in a dictionary.
- It's bad practice to rely on equality testing of floating point numbers. See the related article for an explanation.
Python understands and adheres to the standard precedence rules. In particular, operators will be applied in the following order:
- Terms in parentheses
- Multiplication and division
- Addition and subtraction
- 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.