Table of Contents > Programming in Jython > Formatting in Jython

Formatting in Jython

Compared to many other programming languages, formatting is pretty important in Jython. If you want to indicate where one statement ends and another begins in Jython, you simply start a new line. To group commands together in blocks, you indent lines.

When you use the command area in JES, you are using the Jython interpreter. The same formatting rules apply here as when you are writing a program in the program area.


Indentation (Blocks)

Indentation is used to group statements together in blocks of code. Knowing where to indent becomes extremely important when you begin defining loops or placing loops inside functions.

For example, if you write a function that includes a "for" loop, it might look like this:

def addOneToEach(list):
  print "The old list is", list
  print "The new list is"
  for x in list:
    print x+1

The body of the function is indented two spaces, and the body of the "for" loop is indented two more (four) spaces.

One reason that understanding blocks of code is important, is because the variables you use in a block of code, are only valid within that block. In the example above, the variable x is introduced in the "for" loop. If you try to print x outside of the "for" loop block, the computer won't know what x is!

jump to top

Indentation in the Command Area

Use indentation in the Command Area of JES in the same way that you would use indentation in the Program Area. In the Command Area, you should be prepared to see some extra characters at the beginning of each line. The ">>>" characters indicate that Jython is waiting for a new command. The "..." characters indicate that Jython thinks you are in the middle of defining a function or loop. By leaving a line blank at the end of your function or loop definition, you can tell Jython that you are finished.

The example shown above would look like this in the Command Area:

>>> def addOneToEach(list):
... print "The old list is:", list
... print "The new list is:"
... for x in list:
... print x+1
...
>>>

The function body is still indented two spaces, and the body of the for loop is still indented two more (four) spaces. Rmember, if you want to run this function, you need to call it and include the list that you want it to use!

For example:

>>> list1 = 1,4,9,55
>>> addOneToEach(list1)
The old list is: (1, 4, 9, 55)
The new list is:
2
5
10
56
jump to top