BeanShellTutorial:3 Operators

From jWork.ORG
Revision as of 19:20, 27 December 2016 by Jworkorg (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Limitted access. Reguest membership or login to this link first if you are already a member
Contents

Operators

Basics

BeanShell math works like you would expect.

>>> x = 2
>>> y = 3
>>> z = 5
>>> x * y
6
>>> x + y
5
>>> x * y + z
11
>>> (x + y) * z
25

Powers

There is a built in exponentiation operator (two starts), 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