[ Programming Trail >> Java Trail >> Jython >> Basic Jython Tutorial ]
HelloWorld program (HelloWorld.py)
#import the sys module and reference it by sys.
import sys;
print "Hello World"
sys.exit()
Or better
from sys import *;
print "Hello World"
exit() #No prefix required for import statement
Print value of PI (PrintPI.py)
import sys;
#import the math module and reference it by math.
import math;
print "PI = %f" % math.pi
sys.exit()
Or better
import sys as s; #Refer sys as s
import math as m;
print "PI = %f" % m.pi
del m #undo math import, can not use 'm' below this
s.exit()
User Input (userinput.py)
x = raw_input("Please enter your name:")
print "Hello " + x
if..elif (ifelif.py)
x = int(raw_input("Please enter a number:"))
if x < 0:
print "Negative Number"
elif x == 0:
print "Zero"
elif x > 0:
print "Positive Number"
For Loop (forloop.py)
for x in [1, 2, 3]:
print x
While Loop (whileloop.py)
#Fibonacci Series
a, b = 0, 1
while b < 10:
print b, #Trailing comma avoids new line
a, b = b, a+b #Remember same indentation and no lone break
another example
x = int(raw_input("Please guess the lucky number:"))
while 1:
if x == 5:
print "Congratulations, you win !!"
break
else:
x = int(raw_input("Please guess another number:"))
Range Function (testrange.py)
print range(10) #Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print range(3, 10) #Output: [3, 4, 5, 6, 7, 8, 9] i.e. from 3 to 10
print range(3, 10, 2) #Output: [3, 5, 7, 9] i.e. from 3 to 10 every 2nd
Function Declaration (printx.py)
def func(x):
print x
func(2)
Check Jython.jar classpath (Jython classpath)
import java
print java.lang.System.getProperties()['java.class.path']
Output:
C:\jython-2.1\jython.jar
Show Swing (Call Java) (ShowWindow.py)
import javax.swing as swing
win = swing.JFrame("Hello World")
win.size = (200, 100)
win.show()
Run Python from Java
import org.python.core.*;
import org.python.util.*;
public class HelloWorldPy {
public static void main(String[] args) {
PySystemState.initialize();
PythonInterpreter intrp = new PythonInterpreter();
intrp.execfile("C:\\eclipse\\workspace\\MyJythonProject\\src\\HelloWorld.py");
}
}
References [1]http://www.catalysoft.com/articles/GoodAboutJython.html
Contributors
Jyotirmaya Nanda
I block the IP address(es) of users trying to vandalize my wiki. A simple mail to me can remove your IP from the blocked list. If you are new to wiki and want to try something out please do so at the Wiki Sand Box. Thank you !!.
|