Jython
Variables
To define a variable in the Python language, name it using an identifier. Identifiers can consist of any ordering of letters, numbers, or underscores. An identifier must always begin with a non-numeric character value.
Python does not give any type for the value, which allows any variable to hold any type of data. A variable originally assigned with an integer, can later contain a String. For example, we can assign an integer value to a variable, and later change it to a float.
> x = 5
> y = 1.44
> x = x * y
> print x 7.2Reserved words which cannot be used as variables:
and assert break class continue def del elif else except exec finally for from global or pass raise return try while with yield
Indentation
Python uses indentation rather than punctuation to define the structure of code. As long as the first line of a code block is out-dented by at least one space, the rest of the block can maintain a consistent indentation. Four characters is standard
x = 100 if x > 0: print 'x is greater than 0' else: print 'Incorect indentation?'
The def statement
Functions are named portions of code that perform one or more tasks and return a value. To define a function we use the def statement.
def my_function_name(parameter_list): implementationdef precedes the function name and parameter list when defining a function.
def my_function(): print 'My basic function' ... my_function() My basic functionFunctions w/parameters:
def multiply_nums(x, y): return x * y multiply_nums(10, 5) 50Functions can be passed as parameters to other functions if needed. For example:
def perform_math(oper): return oper(5, 6) perform_math(multiply_nums) 30
Classes
Classes are defined using the class keyword and can contain functions, methods, and variables. Like functions, methods are created using the def keyword. Methods take a parameter known as self that refers to the object to which the method belongs.
Classes contain what is known as an initializer method, and it is called automatically when a class is instantiated.
class my_object: def __init__(self, x, y): self.x = x self.y = y def mult(self): print self.x * self.y def add(self): print self.x + self.y obj1 = my_object(7, 8) obj1.mult() 56 obj1.add() 15In this example, we define a class named my_object which accepts parameters, x and y.
A class initializer method named __init__() initializes values used in the class. An initializer also defines what values can be passed to a class in order to create an object. Each method and function within the class accepts the self argument. This is how the class shares variables.
Statements
Statement Keywords:
if-elif-else for while continue break try-except-finally assert def del raise import
if-elif-else Statement
Evaluate an expression.
x = 3 y = 2 if x == y: print 'x is equal to y' elif x > y: print 'x is greater than y' else: print 'x is less than y' x is greater than y
print Statement
Display program output onto the screen
> print 'Print text to stdout' > my_value = 'I love programming in Jython' > print my_value I love programming in Jython > print 'I like programming in Java, but ' + my_value I like programming in Java, but I love programming in JythonBecause the type of the first operand, is a string, the parser treates the (+) operator as a concatenation operator, not as an addition operator. If you try to append a numeric value to a String you will end up with an error.
> z = 10 > print 'I am a fan of the number: ' + z Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objectsPython formatting options.
%s String %d Decimal %f Float To include the contents of a variable or the result of an expression...
print 'String of text goes here %d %s %f' % (decimalValue, stringValue, floatValue)
Each of the formatting operators, which are included in the string of text, will be replaced with the corresponding values from those variables at the end of the print statement. The % symbol between the line of text and the list of variables tells Python that it should expect the variables to follow, and that the value of these variables should be placed within the string of text in their corresponding positions.
string_value = 'hello world'
float_value = 3.998
decimal_value = 5
print 'Print statement using the values: %d, %s, and %f' % (decimal_value, string_value, float_value)
Print statement using the values: 5, hello world, and 3.998000Using expressions as opposed to variables within our statement.
x = 1
y = 2
print 'The value of x + y is: %d' % (x + y)
The value of x + y is: 3Different formatting operators.
x = 2.3456
print '%s' % x
2.3456
print '%d' % x
2
print '%f' % x
2.345600
try-except-finally
The try-except-finally method performs error handling within a Python application.
# Calculate a value and assign it to x x = 2.14 y = 0 try: print 'The rocket trajectory is: %f' % (x/y) except: print 'Houston, we have a problem. Houston, we have a problem.Place cleanup code within the finally clause of the block. All code within the finally clause is always invoked before the exception is raised.
raise Statement
Place a raise statement anywhere that you wish to raise a specified exception. There are a number of defined exceptions within the language which can be raised. For instance, NameError is raised when a specific piece of code is undefined or has no name.> raise NameError Traceback (most recent call last): File "<stdin>", line 1, in <module> NameErrorTo specify your own message raise a generic Exception...
> raise Exception('Custom Exception') Traceback (most recent call last): File "<stdin>", line 1, in <module> Exception: Custom Exception
import Statement
The import statement brings external modules or code into a program.
If a class is stored in an external module that is named the same as the class itself, the import statement can be used to explicitly bring that class into an application. To import only a specific identifier from another module into the current module, specific code can be named within using syntax...
from <<module>> import <<specific code>>.
For example:
# Import a module named ApogeeCalc import ApogeeCalc # Import a function apogeeCalc from within a module called ExternalModule.py from ExternalModule import apogeeCalcTo import a module named the same as another identifier in the current program, use the as syntax.
import apogeeCalc as apogee
Iteration
A list contains objects or values that can be indexed.
> my_numbers = [1, 2, 3, 4, 5] > my_numbers [1, 2, 3, 4, 5] > my_numbers[1] 2for loop...
> for value in my_numbers: ... print value ... 1 2 3 4 5while loop...
> x = 0 > while x < len(my_numbers): ... print my_numbers[x] ... x = x + 1 ... 1 2 3 4 5The len() function returns the number of elements contained in the list.> x = 9 > y = 2 > while y < x: ... print 'y is %d less than x' % (x-y) ... y += 1 ... y is 7 less than x y is 6 less than x y is 5 less than x y is 4 less than x y is 3 less than x y is 2 less than x y is 1 less than xPython for loop:
> for x in range(10): ... print x ... 0 1 2 3 4 5 6 7 8 9The range function provides a range from one particular value to another. In the example, we pass the value 10 into the range which gives us all values between 0 and 10, inclusive of the zero at the front and exclusive at the end. We see this in the resulting print out after the expression.
Basic Keyboard Input
# The text within the function is optional, and it is used as a prompt to the user > name = raw_input("Enter Your Name:") Enter Your Name:Josh > print name Josh # Use the input function to evaluate an expression entered in by the user > val = input ('Please provide an expression: ') Please provide an expression: 9 * 3 > val 27 # The input function raises an error if an expression is not provided > val = input ('Please provide an expression: ') Please provide an expression: My Name is Josh Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1 My Name is Josh ^ SyntaxError: invalid syntax