Screenshot CONTENTS Screenshot

Appendix A. Jython Statements and Built-In Functions Quick Reference

Java graphics chic01.gif This appendix includes two alphabetically sorted, quick-reference tables. Table A.1 shows built-in functions, and Table A.2 shows Jython statements.

Table A.1. Built-In Functions Quick Reference

Function

Description

abs

Returns the absolute value of the number x.

Syntax:

abs(number)


Example:

>>> abs(-5.43)
5.43

apply

Calls an object, the object supplied as the first argument to the apply function. This can be a function, class, or any callable object. If the optional second argument is supplied, it must be a tuple and is used as ordered arguments when the object is called. The optional third argument can be a Pydictionary or PyStringMap and is used as keyword arguments when the object is called.

Syntax:

apply(object[, args[, kwargs]])


Example:

>>> def printKWArgs(**kw):
... print kw
...
>>> apply(printKWArgs, (), globals())
{'__name__': '__main__', 'printKWArgs': <function printKWArgs at 2744202>, '__doc__': None}
>>>
>>> def product(x, y):
... return x * y
...
>>> print apply(product, (3, 4))
12

callable

Returns 1 or 0 (true or false) as to whether the object in question is a callable type.

Syntax:

callable(object)


Example:

>>> def myFunction():
... return
...
>>> callable(myFunction)
1
>>> callable("a string")
0

chr

For integers <= 65535, chr returns the character (PyString of length 1) that has the specified integer value.

Syntax:

chr(integer)


Example:

>>> chr(119)
'w'
>>> chr(88)
'X'
>>> chr(50000)
u'\uC350'

cmp

Requires two parameter and returns a value of -1, 0, or 1 is returned based on whether x<y, x==y, or x>y, respectively.

Syntax:

cmp(x, y)


Example:

>>> cmp(1, 3)
-1
>>> cmp(3, 1)
1
>>> cmp(3, 3)
0

coerce

Accepts two objects as parameters, tests if there is a common type that can represent the values of each object. The two values are returned in a tuple of same-type objects if there is a common type. If not, coerce raises a TypeError.

Syntax:

coerce(x, y)


Example:

>>> coerce(3.1415, 6) # float and int
(3.1415, 6.0)
>>>results = coerce("a", 2.3)
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: number coercion failed

compile

Compiles a string to a code object. The first parameter is the source string. The second must be a string usually representing the filename. This second argument is used only to make a more descriptive error message so can be any arbitrary string without affecting functionality. The third argument is the mode of compilation, which must be one of three modes:

exec for modules or larger code strings

single for a single statement

eval for an expression

The returned code object can be executed with the exec or eval statement.

Syntax:

compile(source, filename, mode)


Example:

>>> co = compile("0 and 'This' or 1 and
'that'", "-", "eval")
>>> exec(co)
>>> eval(co)
'that'
>>> co = compile("for x in range(10):\n\tprint x,
Java graphics ccc.gif",
"<console>", "single")
>>> exec(co)
0 1 2 3 4 5 6 7 8 9

complex

Returns a complex number where the real and imaginary parts are created from the two arguments supplied to the function. The complex portion (second argument) is optional, and 0 is used when this argument is not supplied.

Syntax:

complex(real[, imag])


Example:

>>> complex(2) # int to complex
(2+0j)
>>> complex(3.1, 0.123) # floats to complex
(3.1+0.123j)
>>> complex("2.1", "0.1234")
(2.1000000000000001+0j)

delattr

Deletes a specified attribute from an object.

Syntax:

delattr(object, name)


Example:

>>> class cache:
... pass # empty class to store arbitrary Java graphics ccc.gifobjects
...
>>> c = cache()
>>> c.a = 1
>>> c.b = 2
>>> vars(c)
{'a': 1, 'b': 2}
>>> delattr(c, "a")
>>> vars(c)
{'b': 2}

dir

If an object is specified, dir returns a list of names defined in that object. If no object is specified, it returns names defined in the current scope.

Syntax:

dir([object])


Example:

>>> a = 1
>>> b = "a string"
>>> def aFunction():
... return
...
>>> dir()
['__doc__', '__name__', 'a', 'aFunction', 'b', Java graphics ccc.gif'file']
>>> dir(aFunction)
['__dict__', '__doc__', '__name__', Java graphics ccc.gif'func_closure',
'func_code', 'func_defaults', 'func_doc',
'func_globals', 'func_name']

divmod

Returns both the integer division and modulus of x divided by y as a tuple.

Syntax:

divmod(x, y)


Example:

>>> divmod(9,4)
(2, 1)
>>> divmod(7, 2)
(3, 1)

eval

Evaluates a string of code, or a code object created with compile. If namespaces are not specified, the current namespaces are used. If only the globals namespace is supplied, it serves locals as well. Namespaces can be PyDictionaries or PyStringMap.

Syntax:

eval(source[, globals[, locals]])


Example:

>>> eval("x>3 and x or 0", {'x':4})
4
>>> eval("x>3 and x or 0", {'x':2})
0
>>> co = compile("map(lambda x: divmod(x,3), L)",
"console", "eval")
>>> eval(co, {'L':range(15)})
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), Java graphics ccc.gif(2,
0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (4, Java graphics ccc.gif0),
(4, 1), (4, 2)]

execfile

Executes a file containing Jython code in the specified namespaces. If namespaces are not specified, the current namespaces are used. If only the globals namespace is supplied, it serves locals as well. Namespaces can be PyDictionaries or PyStringMap.

Syntax:

execfile(filename[, globals[, locals]])


Example:

>>> # first use an anonymous dictionary for Java graphics ccc.gifglobals
>>> execfile("c:\\windows\\desktop\\testfile.py", Java graphics ccc.gif{})
a b 7
>>> globals()
{'__name__': '__main__', '__doc__': None}
>>>
>>> # Now use current namespaces
>>> execfile("c:\\windows\\desktop\\testfile.py")
a b 7
>>> globals()
{'var2': 'b', 'var1': 'a', '__doc__': None, Java graphics ccc.gif'var3': 7,
'__name__': '__main_'}

filter

The filter function requires a function and a sequence as arguments and returns a list of those members of the argument sequence for which the function evaluates to true. The function can be None. In that case, filter returns a list of those members of the argument sequence that evaluate to true.

Syntax:

filter(function, sequence)


Example:

>>> filter(lambda x: x%2, [1,2,3,4,5,6,7,8,9])
[1, 3, 5, 7, 9]
>>> filter(None, [1, 0, [], 3-3, {}, 7])
[1, 7]

float

Returns the first argument, converted to a float (PyFloat type) when possible.

Syntax:

float(x)


Example:

>>> float(2) # int to float
2.0
>>> float(7L) # long to float
7.0
>>> float(abs(1.1+2.1j))
2.3706539182259396
>>> float("2.1") # string to float
2.1

getattr

Returns a reference to the specified object attribute. The two arguments required are the object and the attribute name as a string. An optional third argument is the default value to return if the object does not contain the specified attribute. In the case where the object lacks the desired attribute, and the optional third parameter is absent, an AttributeError is raised.

Syntax:

getattr(object, name[, default])


Example:

>>> from time import time
>>> class util:
... def __init__(self):
... self.inittime = time()
...
>>> u = util()
>>> getattr(u, "inittime")
9.8829678293E8
>>> getattr(u, "currenttime", time())
9.8829681275E8

globals

Returns a dictionary-like object representing the variables defined in the globals namespace.

Syntax:

globals()


Example:

>>> num = 1
>>> string = "a String"
>>> globals()
{'num': 1, '__name__': '__main__', '__doc__': Java graphics ccc.gifNone,
'string': 'a String'

hasattr

Tests whether an object has a specified attribute and returns 1 or 0 accordingly.

Syntax:

hasattr(object, name)


Example:

>>> class add:
... def __init__(self):
... pass
... def methodA(self):
... pass
...
>>> hasattr(add, "methodA")
1
>>> hasattr(add, "methodB")
0

hash

Returns an integer that is the specified object's hash value.

Syntax:

hash(object)


Example:

>>> a = 1
>>> hash(1)
1
>>> hash(a)
1
>>> c = "dog"
>>> hash(c)
1528775661

hex

Returns the hexadecimal representation of an integer as a string.

Syntax:

hex(number)


Example:

>>> hex(16)
'0x10'
>>> hex(15)
'0xf'

id

Returns an integer representing the unique identification of the specified object.

Syntax:

id(object)


Example:

>>> string = "A"
>>> id("A")
6262933

input

The function input is the same as raw_input except that what is entered at the prompt is evaluated.

Syntax:

input([prompt])


Example:

>>> input("Enter a Jython expression: ")
Enter a Jython expression: 2+3
5 <- the evaluated result of 2++3

int

Returns the first argument, converted to an integer (PyInteger type) when possible. The optional second parameter is the base used while converting (16 for hex, 8 for octal) and applies only when converting strings. Converting from a complex number to an int is only possible using the absolute value of the complex number (abs()). Floating-point values are truncated, not rounded.

Syntax:

int(x[, base])


Example:

>>> int(3.5) # float to int
3
>>> int(5L) # long to int
5
>>> int(abs(2.2+1.72j)) # complex to int
2
>>> int("012", 8) # octal string to int
10
>>> int("0x1A", 16) # hex string to int
26

intern

This places the specified string in a PyStringMap of longlived strings and returns the interned string object itself.

Syntax:

intern(string)


Example:

>>> string1 = "a"
>>> Istring1 = intern(string1)
>>> id(string1), id(Istring1)
(7347538, 7347538)

isinstance

Returns 1 or 0 (true or false) according to whether the instance is in fact an instance of the supplied class.

Syntax:

isinstance(instance, class).


Example:

>>> import java
>>> hm = java.util.HashMap()
>>> isinstance(hm, java.util.HashMap)
1
>>> isinstance(hm, java.util.AbstractMap)
1
>>> isinstance(hm, java.util.Vector)
0

len

Returns the length of a sequence or mapping type.

Syntax:

len(object)


Example:

>>> len("a string")
8
>>> len([1,2,3,4,5])
5
>>> len(range(0,100,7))
15


Function Description

list

Accepts one argument that must be a sequence and returns a list with the same members as those in the argument.

Syntax:

list(sequence)


Example:

>>> list("abcdefg")
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> list(("a", "b", "c", "d", "e", "f", "g"))
['a', 'b', 'c', 'd', 'e', 'f', 'g']

locals

Returns a PyStringMap containing variables defined in the locals namespace.

Syntax:

locals()


Example:

>>> def aFunction():
... aVariable = "String var"
... print locals()
...
>>> aFunction()
{'aVariable': 'String var'}

long

Returns the first argument, converted to a long integer (PyLong type) when possible. The optional second parameter is the base used while converting (16 for hex, 8 for octal) and applies only when converting strings. Converting from a complex number to a long is only possible using the absolute value of the complex number (abs()). Floating-point numbers are truncated, not rounded.

Syntax:

long(x, base)


Example:

>>> long(2.7) # float to long
2L
>>> long(abs(1.1+2.3j)) # complex to long
2L
>>> long("021", 8) # octal string to long
17L
>>> long("0xff", 16) # hex string to long
255L

map

The map function requires a function and one or more sequences as arguments. The function is called for each member of the sequence(s) with a number of parameters equal to the number of sequences supplied. If there are sequences of differing lengths, iterations continue until the largest sequence is exhausted, while shorter sequences are padded with None. What is returned is a list containing the results of each call to the function. The function can be None, and in that case, the returned list is the accumulated arguments generated from iteration through the sequence(s).

Syntax:

map(function, sequence[, sequence, ...])


Example:

>>> map(None, range(6), ["a", "b", "c"])
[(0, 'a'), (1, 'b'), (2, 'c'), (3, None), (4, Java graphics ccc.gifNone),
(5, None)]
>>> def pad(string):
... return string.rjust(10)
...
>>> map(pad, ["a", "b", "c", "d"])
[' a', ' b', ' c', '
d']

max

Returns the largest member of specified sequence. The argument must be a sequence.

Syntax:

max(sequence)


Example:

>>> max(1,2,3,4,5,6,7,8,9)
9
>>> T = ("strings", "are", "compared",
"lexigraphically")
>>> max(T)
'strings'

min

Returns the smallest member of the specified sequence. The argument must be a sequence.

Syntax:

min(sequence)


Example:

>>> min(1,2,3,4,5)
1
>>> T = "min returns the smallest char of a Java graphics ccc.gifstring"
>>> min(T)
' '

oct

Returns the octal representation of an integer as a string.

Syntax:

oct(number)


Example:

>>> oct(8)
'010'
>>> oct(7)
'07'

open

Requires a platform-specific file path and name, then opens this designated file and returns the associated file object. The optional mode parameter specifies whether the file is to be opened for reading, writing, appending, or a combination of those. The mode also specifies if the file is binary. Jython requires binary mode be specified to read and write binary data—this is different from CPython. If no mode argument is provided, non-binary, read mode is assumed. Possible values for mode are as follows:

r = reading

w = writing

a = appending

+ = Appended to r, w, or a to designate reading plus writing, or reading plus appending.

b = binary mode.

The optional third parameter to the open function designates buffering. the third parameter is currently ignored in Jython.

Syntax:

open(filename[, mode[, buffering]])


Example:

>>> # open file in current directory for reading
>>> # plus writing.
>>> fo = open("config.cfg", "r+")
>>>
>>> # Open file for binary reading
>>> fo = open("c:\soot\baf\Baf.class", "rb")

ord

Returns the integer value of a character. This function is the opposite of chr(integer). For character c, chr(ord(c))==c.

Syntax:

ord(character)


Example:

>>> ord('w')
119
>>> ord('X')
88
>>> ord(u'\uC350')
50000

pow

Returns x**y. If z is provided, it returns x**y % z.

Syntax:

pow(x, y[, z])


Example:

>>> pow(3, 3)
27
>>> pow(3, 3, 2)
1

range

Returns a list of integers built based on the start, stop, and step parameters. All arguments must be integers (PyInteger or PyLong). Counting starts at the designated start number, or 0. Counting continues to, but not including, the designated stop integer. If the optional step argument is provided, it is used as the increment number.

Syntax:

range([start,] stop [, step])


Example:

>>> range(4)
[0, 1, 2, 3]
>>> range(3, 6)
[3, 4, 5]
>>> range(2, 10, 2)
[2, 4, 6, 8]

raw_input

Reads a string from standard input with the trailing newline removed.

Syntax:

raw_input([prompt])


Example:

>>> name = raw_input("Enter your name: ")
Enter your name: Bilbo Baggins
>>> print name Bilbo Baggins

reduce

Reduces a list of values to one value. The two required arguments are a function and a sequence. The third, optional argument is an initial value.The function provided must have two parameters. The reduction happens by applying the function to the first two sequence members, or the initial value and first sequence member if an initial value is supplied. The function is next applied to the results of this first operation and the next sequence member. This cycle continues until the sequence is exhausted and a single value is returned.

Syntax:

reduce(function, sequence[, initial])


Example:

>>> def add(x, y):
... return x + y
...
>>> reduce(add, [5,4,3,2,1])
15
>>> def stripspaces(x, y):
... return x.strip() + y.strip()
...
>>> reduce(stripspaces, "A string with spaces")
'Astringwithspaces'

reload

Reloads a specified module.

Syntax:

reload(module)


Example:

>>> import math
>>> # If the math module changed- reload it.
>>> reload(math)
<jclass org.python.modules.math at 1401745>

repr

Returns a string that represents the specified object.

Syntax:

repr(object)


Example:

>>> repr(123)
'123'
>>> repr(type)
'<java function type at 4737674>'
>>> repr("A string")
"'A string'"

round

Returns a floating-point number representing the numeric argument. If the optional argument for the number of significant digits to round to is absent, the number is rounded to 0 decimal places. Otherwise, the number is rounded to the specified number of significant digits from the decimal point. Negative ndigits numbers mean left of the decimal, positive means right of the decimal. The ndigits argument must be an integral number in Jython, which slightly differs from CPython's acceptance of anything convertible to an integer.

Syntax:

round(number[, ndigits])


Example:

>>> round(1.23434, 3L)
1.234
>>> round(23.2124)
23.0
>>> round(2)
2.0

setattr

Sets an object's attribute to a value. The three required arguments are the object, the attribute name as a string, and the value. In Jython, you can set arbitrary attributes on Jython objects, but not on Java objects. This means using setattr to set a previously absent attribute works for Jython objects, but a TypeError is raised for Java objects.

Syntax:

setattr(object, name, value)


Example:

>>> class split:
... def __init__(self, token):
... self.token = token
...
>>> s = split(":")
>>> vars(s)
{'token': ':'}
>>> setattr(s, 'count', 0)
>>> setattr(s, 'token', ",")
>>> vars(s)
{'token': ',', 'count': 0}
>>>
>>> # Java objects are different for arbitraryattributes>>>
# Note that javax.midi is an optional package- you may need to download it
>>> # for this example to work.
>>> from javax.sound.midi import VoiceStatus
>>> v = VoiceStatus()
>>> v.channel
0
>>> setattr(v, "channel", 3)
>>> v.channel # "channel" already exists- this Java graphics ccc.gifworks
3
>>> v.channel
3
>>> v.arbitraryVar = 6 # "arbitraryVar doesn't Java graphics ccc.gifexist Traceback (innermost last):
 File "<console>", line 1, in ?
TypeError: can't set arbitrary attribute in java instance: arbitraryVar

slice

The slice function is a synonym for sequence slice syntax. The slice object returned from this function can replace traditional slice notation.

Syntax:

slice([start,] stop[, step])


Example:

>>> L = ["s", "o", "r", "c", "q", "a", "p", "j"]
>>> sliceobj = slice(7, 0, -2)
>>> L[sliceobj]
['j', 'a', 'c', 'o']

str

Returns a string representation of an object.

Syntax:

str(object)


Example:

>>> str(1) # int to string
'1'
>>> str(4L) # long to string
'4'
>>> str(2.2+1.3j)
'(2.2+1.3j)'
>>> from java.util import Vector
>>> str(Vector)
'java.util.Vector'
>>> v = Vector()
>>> str(v)
'[]'
>>> v.add(type) # put a function in the vector
1
>>> str(v)
'[<java function type at 5229978>]'

tuple

Accepts one argument that must be a sequence and returns a tuple with the same members as those in the argument.

Syntax:

tuple(sequence)


Example:

>>> tuple([1,2,3,4,5]) # list to tuple
(1, 2, 3, 4, 5)
>>> tuple("This is a test") # string to tuple
('T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ',
't', 'e', 's', 't')

type

Returns an object's type—usually the name of the class in the org.python.core package that represents objects of that type.

Syntax:

type(object)


Example:

>>> type("a string")
<jclass org.python.core.PyString at 1923370>

unichr

This does the same as chr. These two methods, chr and unichr, exist for compatibility with CPython.

Syntax:

unichr(i)


Example:

See chr

unicode

This creates a new PyString object using the specified encoding. Available encodings reside in Jython's Lib directory within the encodings folder. The optional errors argument can be either strict, ignore, or replace.

Syntax:

unicode(string [, encoding[, errors]])


Example:

>>> unicode("Abél", "utf_8", "replace")
u'Ab\uFFFDl'

vars

If an object is specified, vars returns a dictionary of names bound within that object. The object must have an internal __dict__ attribute. If no object is specified, vars does the same as locals().

Syntax:

vars([object])


Example:

>>> class aClass:
... def __init__(self):
... attrib1 = "An instance variable"
... attrib2 = "Another instance variable"
...
>>> vars(aClass)
{'__init__': <function __init__ at 634037>,
'__module__': '__main__', '__doc__': None}
>>> vars()
{'aClass': <class __main__.aClass at 7033304>,
'__name__': '__main__', '__doc__': None}

xrange

The xrange function does the same as the range function. The difference is that the xrange function returns an xrange object that generates numbers when needed as opposed to generating the entire list at once. This is beneficial for extremely large ranges.

Syntax:

xrange([start,] stop [, step])


Example:

See range

zip

Returns a list of tuples of a length equal to the shortest sequence supplied as an argument. The tuples contain all sequence items with the same index, and each tuple has a length equal to the number of sequences supplied.

Syntax:

zip(seq1 [, seq2 [...]])


Example:

>>> zip([1,2,3,4,5,6,7], "abcdefg")
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'),
Java graphics ccc.gif (6,
'f'), (7, 'g')]
>>> zip(range(5), range(5,-1,-1))
[(0, 5), (1, 4), (2, 3), (3, 2), (4, 1)]

 

Table A.2. Jython Statements Quick Reference

Statement

Description

assert

The assert statement tests whether an expression is true and raises an exception if it is not true. If two expressions are supplied, they are treated as an OR so if either is true, and exception is not raised. Setting __debug__=0, and possibly the -O command-line switch in future releases, disables asserts.

Syntax:

"assert" expression [, expression]


Example:

>>>a=21
>>>assert a<10
Traceback (innermost last):
 File "<console>", line 1, in ?
AssertionError:

break

The break statement terminates execution of an enclosing loop and continues execution after the loop block. This means it does skip the else block if it exists.

Syntax:

"break"


Example:

>>>for x in (1,2,3,4):
... if x==3:
... break
... print x
...
1
2
>>>

class

Designates the start of a class definition.

Syntax:

"class" name[(base-class-name(s))]:


Example:

>>>class test: # no base class
... pass # place holder
...
>>>t = test() # Calls class to create an Java graphics ccc.gifinstance

continue

The continue statement halts execution of the current loop block and starts the enclosing loop again at its next iteration.

Syntax:

"continue"


Example:

>>>for x in (1,2,3,4):
... if x==3:
... continue
... print x
...
1
2
4
>>>

def

Designates the start of a function or method definition.

Syntax:

"def" name(([parameters]):
 code-block


Example:

>>> def caseless_srch_n_replace(string, srch, Java graphics ccc.gifrplc):
... return string.lower().replace(srch, rplc)
...
>>> S = "Some UseLess text"
>>> caseless_srch_n_replace(S, "useless", Java graphics ccc.gif"useful")
'some useful text'

del

The del statement removes a variable from the namespace in which del was called.

Syntax:

"del" identifier


Example:

>>>a="foo"
>>>print a foo
>>>del a
>>>print a Traceback (innermost last):
 File "<console>", line 1, in ?
NameError: a

exec

Executes a string, open file object, or a code object supplied as the first expression following the exec statement. The second and third expressions are optional and represent the PyDictionary or PyStringMapping objects to use as the global and local namespaces. If only globals is supplied, locals defaults to it. If neither namespace is supplied, the current namespaces are used.

Syntax:

"exec" expression ["in" expression ["," Java graphics ccc.gifexpression]]


Example:

>>>exec("print 'The exec method is used to print this'")
The exec method is used to print this

for

The for statement is a loop structure that repeats an associated block of code for each member of a sequence or until a break statement occurs. Therefore, the expression provided must evaluate to a sequence. There is an implicit name binding of each sequence value to the variable(s) specified after the for statement. Execution of the optional else clause occurs after the full sequence has expired (meaning it is not executed if a break statement appeared in the loop block).

Syntax:

"for" variable "in" expression":"
 code-block
["else:"]
 code-block


Example:

>>> for x in (1, 2, 3):
... print x, "in first code-block"
... else:
... print "In second code-block"
...
1 in first code-block
2 in first code-block
3 in first code-block In second code-block

global

Explicitly designates that the designated name be referenced from the globals namespace instead of locals.

Syntax:

"global" identifier ["," identifier]*


Example:

>>> var = 10
>>> def test():
... global var
... print var # try and print the global identifier 'var'
... var = 20 # assign to 'var' in local namespace
...
>>> test()
10

if

The if statement designates conditionally executed blocks of code. Code blocks can be defined for if, elif, and else statements. Only the first approved code block executes as determined by the trueness of its expressions. The code block executed is the first block whose expression evaluates to true, or the else block if all other expressions evaluate to false.

Syntax:

"if" expression:
 code-block
"elif" expression:
 code-block
"else":
 code-block


Example:

>>>a, b = 0, 1
>>>if a==b:
... print "variable a equals variable b"
...elif a>b:
... print "variable a is greater than b"
...else:
... print "variable a is less than b"
...
variable a is less than b

import

Imports the specified Jython package, Jython module, Java package, or Java class. This creates a name binding within the namespace import was called. You can optionally change the name imports are bound to with an as modifier.

Syntax:

import module-name


OR

from module-name import names


OR

import module-name as new-name


Example:

>>>import sys
>>>from java import util
>>>import os as myOS
>>>from sys import packageManager as pm

pass

The "do nothing" statement. This statement is a placeholder.

Syntax:

"pass"


Example:

>>> for x in (1,2,3,4):
... pass
...
>>>def doNothing():
... pass

print

Evaluates an expression, converts the result to a string if needed and writes the string to sys.stdout or whatever file-like object it is directed to with the >> syntax. A filelike object is one with a write method defined.

Syntax:

"print" [expression]


OR

"print >> " fileLikeObject,, [expression]


Example:

>>> print "Hello world"
Hello world
>>> print >> myFile, "Hello world"
>>>

raise

The raise statement raises an exception. It precedes three optional expressions that represent exception type, value, and traceback. The type can be the exception class, a string representing the exception class, or an instance of the exception class. The value, or second expression, is a constructor parameter for the exception class. The exception's constructor receives one argument unless the second expression evaluates to a tuple; in that case, the tuple indexes are separate arguments. If the first expression in the raise statement is an instance, the second, or value expression must be None. The optional third expression must be a traceback object.

Syntax:

"raise" [expression [, expression [, traceback]]]


Example:

>>> raise ValueError, "No value provided"
Traceback (innermost last):
 File "<console>", line 1, in ?
ValueError: no value provided

return

Terminates execution of the method or function it is within, and returns the value of the evaluated expression it prefixes. If there is no expression, return returns None.

Syntax:

"return" [expression]


Example:

>>> def someFunction():
... return "This string is the return value"
...
>>> print someFunction()
This string is the return value

try/except

The try/except statement is Jython's exception-handling mechanism, similar to Java's try/catch statement. The try block of code executes until completion or until an error. If there is an error (an exception was raised), control immediately switches to searching for an appropriate except clause to handle the exception. If the try/finally syntax is used, the finally block is executed regardless of any exceptions in the try block.

Syntax:

"try:" code-block
"except" [expression ["," target]] ":" code-block
["else:" code-block]


OR

"try:" code-block
"finally:" code-block


Example:

>>> try:
... 1/0
... except ZeroDivisionError, e:
... print "You cannot divide by zero: ", e
...
You cannot divide by zero: integer division or Java graphics ccc.gifmodulo
>>>
>>> try:
... pass
... finally:
... print "This block always executes"
...
This block always executes

while

The while statement is a loop structure that executes a block of code as long as a provided expression evaluates to true or until a break statement.

Syntax:

"while" expression ":"


Example:

>>> x = 10
>>> while x>0:
... print x,
... x -= 1
...
10 9 8 7 6 5 4 3 2 1 >>>

 

Screenshot CONTENTS Screenshot
Comments