Python math works as expected:
>>>x=2>>>y=3>>>z=5>>>x*y6>>>x+y5>>>y-x1>>>x*y+z11>>>(x+y)*z25>>>3.0/2.0# True division1.5>>>3//2# Floor division1>>>2**3# Exponentiation8
Note that Python adheres to the PEMDAS order of operations.
There is a built in exponentiation operator**, which can take either integers, floating point or complex numbers. This occupies its proper place in the order of operations.
>>>2**8256
In Python 3.x, slash operator ("/") doestrue division for all types including integers, and therefore, e.g.3/2==1.5
[1][2]. The result is of a floating-point type even if both inputs are integers: 4 / 2 yields 2.0.
In Python 3.x and latest 2.x,floor division for both integer arguments and floating-point arguments is achieved by using the double slash ("//") operator. For negative results, this is unlike the integer division in the C language since -3 // 2 == -2 in Python while -3 / 2 == -1 in C: C rounds the negative result toward zero while Python toward negative infinity.
Beware that due to the limitations offloating point arithmetic, rounding errors can cause unexpected results. For example:
>>> print(0.6/0.2)3.0>>> print(0.6//0.2)2.0
For Python 2.x, dividing two integers or longs using the slash operator ("/") usesfloor division (applying thefloor function after division) and results in an integer or long. Thus, 5 / 2 == 2 and -3 / 2 == -2. Using "/" to do division this way is deprecated; if you want floor division, use "//" (available in Python 2.2 and later). Dividing by or into a floating point number will cause Python to use true division. Thus, to ensure true division in Python 2.x:x=3; y=2; float(x)/y == 1.5
.
Links:
The modulus (remainder of the division of the two operands, rather than the quotient) can be found using the% operator, or by thedivmod builtin function. Thedivmod function returns atuple containing the quotient and remainder.
>>>10%73>>>-10%74
Note that -10 % 7 is equal to +4 while in the C language it is equal to -3. That is because Python floors towards negative infinity not zero. As a result, remainders add towards positive infinity. Consequently, since -10 / 7 = -1.4286 becomes floored to -2.0 the remainder becomes x such that -14 + x = -10.
Links:
Unlike some other languages, variables can be negated directly:
>>>x=5>>>-x-5
Operation | Means |
---|---|
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
== | Equal to |
!= | Not equal to |
Numbers, strings and other types can be compared for equality/inequality and ordering:
>>>2==3False>>>3==3True>>>3=='3'False>>>2<3True>>>"a"<"aa"True
The operatorsis
andis not
test for object identity and stand in contrast to == (equals):x is y
is true if and only if x and y are references to the same object in memory.x is not y
yields the inverse truth value.Note that an identity test is more stringent than an equality test since two distinct objects may have the same value.
>>>[1,2,3]==[1,2,3]True>>>[1,2,3]is[1,2,3]False
For the built-inimmutable data types (like int, str and tuple) Python uses caching mechanisms to improve performance, i.e., the interpreter may decide to reuse an existing immutable object instead of generating a new one with the same value. The details of object caching are subject to changes between different Python versions and are not guaranteed to be system-independent, so identity checks on immutable objects like'hello' is 'hello'
,(1,2,3) is (1,2,3)
,4 is 2**2
may give different results on different machines.
In some Python implementations, the following results are applicable:
print(8is8)# Trueprint("str"is"str")# Trueprint((1,2)is(1,2))# False - whyever, it is immutableprint([1,2]is[1,2])# Falseprint(id(8)==id(8))# Trueint1=8print(int1is8)# Trueoldid=id(int1)int1+=2print(id(int1)==oldid)# False
Links:
There is shorthand for assigning the output of an operation to one of the inputs:
>>>x=2>>>x# 22>>>x*=3>>>x# 2 * 36>>>x+=4>>>x# 2 * 3 + 410>>>x/=5>>>x# (2 * 3 + 4) / 52>>>x**=2>>>x# ((2 * 3 + 4) / 5) ** 24>>>x%=3>>>x# ((2 * 3 + 4) / 5) ** 2 % 31>>>x='repeat this '>>>x# repeat thisrepeatthis>>>x*=3# fill with x repeated three times>>>xrepeatthisrepeatthisrepeatthis
Logical operators are operators that act on booleans.
The or operator returns true if any one of the booleans involved are true. If none of them are true (in other words, they are all false), the or operator returns false.
ifaorb:do_thiselse:do_this
The and operator only returns true if all of the booleans are true. If any one of them is false, the and operator returns false.
ifaandb:do_thiselse:do_this
The not operator only acts on one boolean and simply returns its opposite. So, true turns into false and false into true.
ifnota:do_thiselse:do_this
The order of operations here is:not first,and second,or third. In particular, "True or True and False or False" becomes "True or False or False" which is True.
Warning, logical operators can act on things other than booleans. For instance "1 and 6" will return 6. Specifically, "and" returns either the first value considered to be false, or the last value if all are considered true. "or" returns the first true value, or the last value if all are considered false. In Python the numberzero andempty strings, lists, sets, etc. are considered false. You may usebool()
to check whether a thing is considered to be true or false in Python. For instance,bool(0.0)
andbool([])
both returnFalse
.
Python operators for bitwise arithmetic are like those in the C language. They include & (bitwise and), | (bitwise or), ^ (exclusive or AKA xor), << (shift left), >> (shift right), and ~ (complement). Augmented assignment operators (AKA compound assignment operators) for the bitwise operations include &=, |=, ^=, <<=, and >>=. Bitwise operators apply to integers, even negative ones and very large ones; for the shift operators, the second operand must be non-negative. In the Python internal help, this is covered under the topics of EXPRESSIONS and BITWISE.
Examples:
Examples of augmented assignment operators:
Class definitions can overload the operators for the instances of the class; thus, for instance, sets overload the pipe (|) operator to mean set union: {1,2} | {3,4} == {1,2,3,4}. The names of the override methods are __and__ for &, __or__ for |, __xor__ for ^, __invert__ for ~, __lshift__ for <<, __rshift__ for >>, __iand__ for &=, __ior_ for |=, __ixor__ for ^=, __ilshift__ for <<=, and __irshift__ for >>=.
Examples of use of bitwise operations include calculation of CRC and MD5. Admittedly, these would usually be implemented in C rather than Python for maximum speed; indeed, Python has libraries for these written in C. Nonetheless, implementations in Python are possible and are shown in the links to Rosetta Code below.
Links: