Tutorial:Jython/4 Operators

From HandWiki

Operators

Python math works like you would expect.

<jc lang="python"> x = 2; y = 3; z = 5 print x * y print x + y print x * y + z print (x + y) * z </jc>


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.

<jc lang="python"> y=28; print y </jc>

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

<jc lang="python"> x = 5; y=float(x) print y </jc>

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

<jc lang="python"> print 0.6/0.2 print 0.60.2 </jc>

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. <jc lang="python"> print 10%7 </jc>

Negation

Unlike some other languages, variables can be negated directly:

<jc lang="python"> x = 5 print -x </jc>

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