You are a guest. Restricted access. Read more

Operators

Basics

Python math works like you would expect.


x = 2;  y = 3; z = 5
print x * y
print x + y
print x * y + z
print (x + y) * z

Powers

There is a built in exponentiation operator (two stars), which can take either integers, floating point or complex numbers. This occupies its proper place in the order of operations.


y=2**8; print y

Division and Type Conversion

Dividing two integers or longs uses integer division, also known as “floor division” after division. So, for example, 5/2 is 2. ”/” does “true division” for floats and complex numbers; for example, 5.0/2.0 is 2.5.

Dividing by or into a floating point number (there are no fractional types in Python) will cause Python to use true division. To coerce an integer to become a float, 'float()' with the integer as a parameter


x = 5; y=float(x)
print y

This can be generalized for other numeric types: int(), complex(), long(). Beware that rounding errors can cause unexpected results. For example:


print 0.6/0.2
print 0.6//0.2

Modulo

The modulus (remainder of the division of the two operands, rather than the quotient) can be found using the % operator, or by the divmod builtin function. The divmod function returns a tuple containing the quotient and remainder.


print 10%7

Negation

Unlike some other languages, variables can be negated directly:


x = 5
print -x

Augmented Assignment

There is shorthand for assigning the output of an operation to one of the inputs:

>>> x = 2
>>> x # 2
2
>>> x *= 3
>>> x # 2 * 3
6
>>> x += 4
>>> x # 2 * 3 + 4
10
>>> x /= 5
>>> x # (2 * 3 + 4) / 5
2
>>> x **= 2
>>> x # ((2 * 3 + 4) / 5) ** 2
4
>>> x %= 3
>>> x # ((2 * 3 + 4) / 5) ** 2 % 3
1
 
>>> x = 'repeat this  '
>>> x  # repeat this
repeat this
>>> x *= 3  # fill with x repeated three times
>>> x
repeat this  repeat this  repeat this

Boolean

or:

if a or b:
    do_this
else:
    do_this

and:

if a and b:
    do_this
else:
    do_this

not:

if not a:
    do_this
else:
    do_this
python/operators.txt · Last modified: 2013/04/14 16:52 (external edit)
Back to top
CC Attribution-Share Alike 3.0 Unported
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0