NBPythonQuickStart

Python Quick Start Using Netbeans IDE

Submitted by Josh Juneau

Python is an elegant, easy-to-use programming language that is enjoyable to learn and has lots of community support. Even better yet, Netbeans 6.5 makes it possible to use this elegant language from within your favorite IDE. With it's added support for various JVM and non-JVM languages, Netbeans 6.5 opens new doors to programmers giving them an easy-to-use environment for developing in many different languages. Why is learning Python any better than learning another language such as Java? Well, given that Python has a JVM-based alternative known as Jython, learning Python gives you the opportunity to produce software that can be delivered to just about any platform. Given that combined with it's elegant syntax and easy usage, Python is a good candidate to use for developing your applications.

This tutorial is designed to give Python newbies a chance to learn the basics of the language so that they can begin to explore it's possibilities. By no means is this tutorial meant to make anyone a Python expert, but I think that newcomers will find it easy to learn basics the language using this guide, and also learn how to use one of the top development environments for Python...the Netbeans IDE.

Throughout this tutorial, we will be developing a small application (hockeyRoster.py) from the ground-up. We will develop an application to contain and manage our hockey team. In this intro tutorial, will develop a command-line application to add a list of players, their preferred position, and if their current status ("BENCHED" or "ACTIVE") to an external file. At that point, we will be able to list the contents of the file via Python as well as update records. Since this tutorial is an introduction, we will cover file I/O but we will not get into the specifics of using databases with Python. Hopefully that tutorial will be the next in the series!

Let's get started!

Contents


Installing Python and Netbeans

To get started, you will need to perform the following steps:

Download Python and Install - This tutorial will use the Python 2.x versions as 3.0 is not yet compatible with the Jython distribution. Everything you learn here can also be mirrored in the Jython world. This means that you have the choice to deploy your applications on the Java Virtual Machine if you'd like.

Download Netbeans 6.5 - Python EA and Install - For the purposes of this tutorial, it would be fine to download and install the Python EA edition of Netbeans. If you'd prefer to download the entire Netbeans 6.5 IDE then that will also work, just add the Python plugins via the Plugin manager once installed.

Configuring Your Environment

In order to use Netbeans for working with your Python applications, you will need to ensure that your Python platform is configured correctly within the IDE. To do this, go to the Python platform manager which is located in the "Tools" menu of Netbeans. Once open, if you do not see your default Python installation already available, go ahead and select the auto-detect button...this should take care of adding your Python installation as a platform for use within Netbeans. Once completed, your Python Platforms window will look similar to the following, but you may not have the Jython installations (unless you add them as well) and your paths will be different (unless you somehow use the same paths as me).

http://wiki.netbeans.org/attach/DevelopingJythonAppsUsingNetbeans/nbwiki1_2.jpg

Once you've finished setting up your Python platforms, you are ready to begin developing your first Python application. However, we will not do that yet because we would like to become familiar with the language. Netbeans allows you to bring up an interactive Python console which will allow you to test and/or program Python on-the-fly. In order to bring up the interactive Python console, go to the "Window" menu and then choose "PythonConsole". You will see a new output window appear near the bottom of your Netbeans IDE window.

http://wiki.netbeans.org/attach/NBPythonQuickStart/nbquickpython2_NBPythonQuickStart.jpg

Now in order to make things a bit easier to see and use we will get rid of the Netbeans IDE window for the time being. Right-click on the title bar of the output window for the PythonConsole and choose "Undock Window".

http://wiki.netbeans.org/attach/NBPythonQuickStart/nbquickpython3_NBPythonQuickStart.jpg

This will separate the PythonConsole output window from the rest of the IDE...go ahead and minimize Netbeans IDE now so that you only have the undocked PythonConsole window in your view. Now lets learn some basics!

Python Language Basics

Lets face it, most programming languages have the same "basic" functionality. Python is no exception, it gives the ability to define variables, use expressions and conditionals, etc. In this section of the tutorial, we will discuss how to use the basics of the language.

Commenting and Documentation Strings

Commenting in Python is done by using a "#" symbol at the beginning of a line. If you place a "#" symbol at the beginning of a line then all of the text thereafter is treated as a comment. You can also place a # symbol anywhere else in a line of code, and everything that comes after the # will be treated as a comment.


# This is the first comment in our code
firstName = 'Josh'   
lastName = 'Juneau'  # This comment begins after the variable declaration
position = 'center'

If you are writing a module and using classes and functions within, then you can easily document what that class or function does by using documentation strings. A documentation string should appear as the first line after the declaration of a class or function, and it should start with """ and end with """ (triple quotes).


class HockeyRoster:

    """ This class contains the object
         definitions for a hockey roster """

  ...

Defining Variables and Representing Strings

If you are used to defining variables in any other program language then you will find that Python variable definition is not much different. However, if you are only familiar with statically typed languages then you'll soon learn that the dynamic capabilities of Python can be of great value...especially when working with variable definitions. The dynamic tendencies of the language allow one to assign any value to a variable at any given time.

For instance, in the following example you will see that we begin by assigning "x" an integer value, and later assign it a floating point value. Since we are not mandated to statically define a type to a particular variable they can take any given value.

http://wiki.netbeans.org/attach/NBPythonQuickStart/nbquickpython4_NBPythonQuickStart.jpg

As you can see from the example, we can assign any data type to a variable and then change it at will. The last assignment of x changes it from a float to a string, and uses the float definition at the same time. This is something that a statically typed language cannot achieve.

Another key to note from the example above is the notation which we used to represent our string. Much like the C programming language, Python uses the "%d", "%f", "%s" notation to format data within a particular string. We use "%d" to represent a decimal value, "%f" represents a float, and "%s" is a string. If you wish to take it one step further and format the data output within the string, you can use a notation such as "%2d" or "%0.2f" to apply formatting to the values.

Let's apply these concepts to our hockeyRoster.py application. In order to populate one record of our file, we will need to assign a first name, last name, position, and status for a particular player. This is done as follows:

>>> firstName = 'Josh'
>>> lastName = 'Juneau'
>>> position = 'center'
>>> status = 'ACTIVE'
>>> print firstName + " " + lastName
Josh Juneau
>>> print "%s %s is a %s and currently has a status of: %s" % (firstName, lastName, position, status)
Josh Juneau is a center and currently has a status of: ACTIVE

While not earth-shattering, it gives a good feel for assigning variables in Python.

Lists, Tuples, Sets, and Dictionaries

Sequences in Python are objects that are iterable. There are three types of sequences in Python: Lists, Strings, and Tuples. I will cover these object types below, along with a couple of other objects that are related.

Lists

In programming, lists are used all of the time to store values or queue data. Python has an very easy list notation, and they are easy to use too because of the language's dynamic tendencies. Adding and removing values from a Python list is simple, and this makes the flow of data within your applications easier to read.

Lists can be defined using a comma separated list of values within square brackets. When using lists, one can assign different data types within the same list.


>>>listx = [firstList,1,test1]
>>>listx[0] # print the value in position 0
'first'

# Use insert(index,value) to insert a value into the list
>>>listx.insert(1,'test2')
>>> print listx
[firstList,test2,1,test1]

# Use append(value) to add an item to the end of the list
>>>listx.append('test3')
>>>print listx
[firstList,test2,1,test1,test3]

# Use extend(list) to add another list to the list
>>>listy = [list,two]
>>>listx.append(listy)
>>>print listx
[firstList,test2,1,test1,test3,[list,two]

# Removing List Items
# Use del to delete the designated item from the list
>>>del listx[2]
>>>print listx
[firstList,test2,test1,test3,[list,two]

# Find the length of a list
>>>len(listx)
6

Lists can also be sliced using the x:y notation, or concatenated using the + operator. We also have the ability to update the contents of a list. Try these examples using data for hockeyRoster.py in your Netbeans PythonConsole.


>>>listx[1:3}
[test2,test1]

>>>listx[0:4]
[firstList,test2,test1]

Strings are lists of single character values. For instance, if the String "Python" evaluates to the following:

 [P,y,t,h,o,n] 

Tuples

Tuples are data structures that are very similar to lists as they contain an arbitrary collection of values and assign to a variable. However, there are subtle differences between the two data types.


- Lists are mutable, tuples are immutable:  This means that you cannot alter the contents of a tuple once it has been defined, but as you saw in the previous sub-section this is not the case with lists.
- Some would say that lists have order, and that tuples are made for structuring and organizing data.
- One should use a list if he or she wishes to maintain a set of data which can be updated, appended to, or removed from.  Otherwise, a tuple should be used as to make the contents of the data structure "read-only".

Tuples are defined by listing a number of values separated by commas.

Example:

# Define tuple
>>> t = 1,2,3,4

# List tuple value contained within space 0
>>> t[0]
1

# Print the contents of the tuple
>>> t
(1,2,3,4)

# Define an empty tuple
>>> u = ()

# Find length of tuple
>>> len(t)
4

# Combine tuples
>>> u = t,("second","tuple")
((1,2,3,4),("second,"tuple"))


We can retrieve the values of a tuple using the same notation as with a list, by position.

Sets

Sets are containers that hold unordered data values, they cannot contain duplicate values, and they are not indexable. This means that the x y notation does not work with a set. You must use built in set functions in order to work with a set.


# Define list with a duplicate
>>> positions = [center,wing,goalie,wing,defensemen]
# Define a set from that list
>>>myset = set(positions)
>>> myset
set([goalie,center,defensemen,wing])

# Test set membership
>>> 'goalie' in myset
True


Dictionaries

If you've ever worked with set, value pairs in another language then you've basically worked with Python dictionaries. These are containers that allow you to store values in pairs, where you have a key:value notation. Keys must be unique within any given dictionary, but values can be duplicates. As you can see from the examples below, dictionaries can be a very useful data container as they provide capabilities which are not available in lists. You may use any data type you wish as a key as long as it is unique. Strings and integers are most commonly used for keys, but you could also use a tuple since they are immutable. Let's see dictionaries in action...


# Define dictionary
>>> playerPositions = {'juneau':'center', 'nickels':'wing'}

# Add entry into dictionary
>>> playerPositions[smith] = 'defensemen'
>>> playerPositions
{'juneau': 'center', 'nickels': 'wing', 'smith': 'defensemen'}

# Remove entry
>>> del playerPositions[juneau]
>>> playerPositions
{'nickels': 'wing', 'smith': 'defensemen'}


# Test membership
>>> 'nickels' in playerPositions
True

# List keys
>>> playerPositions.keys()
[nickels,smith]


We probably want to be able to pass a list of player data into our application or else it would be tedious to add each player one-by-one. A list of player data would be perfect, now let's learn how to parse that list in the next section.

Iteration and Conditionals

For Loop:

The "for" loop in Python is just like the shorthand notation of a "for" loop which was introduced in Java 1.5. Quite simply, a "for" loop is used to iterate through a list of values as such:


>>> for position in myset:
...     print position
... 
goalie
center
defensemen
wing

If Statement:

No surprise here, the "if" statement evaluates a conditional to a True or False. If you want to perform several comparisons, you will follow the first "if" statement with an "elif", and the last evaluation should be "else". Let's look at the "if" statement in the example below.


>>> juneau = 'forward'
>>> nickels = 'forward'
>>> smith = 'defensemen'
>>> jones = 'goaltender'
>>> if jones == 'forward':
...     print 'Jones is a forward'
... elif jones == 'defensemen':
...     print 'Jones is a forward'
... else:
...     print 'Jones is a goaltender'
... 
Jones is a goaltender

While Statement:

As with other programming languages, the "while" statement will continue to loop until a defined condition is met.


# Represent a team wellness report

>>> players = 18
>>> injuries = 1
>>> while players > 10:
...      players -= injuries
...      if players < 13:
...          'Only %d players left, critical number' % players
...      elif players < 10:
...          'Need more players to make a team'
...      else:
...          'Team is healthy'
... 
'Team is healthy'
'Team is healthy'
'Team is healthy'
'Team is healthy'
'Team is healthy'
'Only 12 players left, critical number'
'Only 11 players left, critical number'
'Only 10 players left, critical number'


Modules

I've mentioned modules earlier in this article and now I will tell you what they are. A module is simply a piece of Python code that is saved to a file with a .py extension. The basic principle behind modules is reuse; whereas we can write some Python code and save it to a file which can later be used by other programs. A module can contain any Python code, whether it be definitions, statements, functions, or classes.

Once you have a module defined, you can use it anywhere by importing it into the Python program as needed. You can import complete modules or just named functions or classes within the module as such.

# Importing a class named Players from a module
from Players import Players

# Importing the complete Players module

import Players

Writing a Quick Python Program Using Netbeans

As I've mentioned earlier in this tutorial, we are going to create a simple application to manage a hockey team roster. Now, this first tutorial will leave a bit to be desired as it will not go into such detail as persisting the roster once it has been created. However, this first small application will give you enough of a taste of Python to get you started.

Lets start by creating your Python application and naming it HockeyRoster. In order to do so, go to the 'File' menu and choose 'New Project'. From within the listing of project types, choose 'Python Project'. Once you've done this the 'New Python Project' window will appear which allows you to name your project, choose Python platform, and determine a location to place your project. Name your project 'HockeyRoster' as shown in the screen shot below. **Note that your paths will be different than mine.

http://wiki.netbeans.org/attach/NBPythonQuickStart/nbpythonquickstart1_1_NBPythonQuickStart.jpg

Once you've created the project it will appear in the project window. Take some time to familiarize yourself with the new Netbeans Python project by right-clicking (CTRL+click) on the project and choosing 'Properties'. Go through the project properties and note the various options which can be set. I really like the option to set a different formatting on a per-project basis myself.

http://wiki.netbeans.org/attach/NBPythonQuickStart/nbpythonquickstart2_NBPythonQuickStart.jpg

Go ahead and create two source files by right-clicking on the 'Sources' folder and choosing 'New'->'Empty Module'. Name the first file "HockeyRoster", and the second "Player". We are going to use the "Player.py" module as a container to hold our player objects. We will place our application's implementation within the "HockeyRoster.py" module.

Place the following code within the "Player.py" module. Note that we are simply creating a Python class to hold our player object. Each player has four attributes (id, first name, last name, and position). We then define a function within that class which will be used to "create" the player...or set the given values into their designated attributes.


# Player.py
#
# Container to hold our player objects

class Player:
    
    # Player attributes

    id = 0
    first = None
    last = None
    position = None

    # Function used to create a player object

    def create(self,id,first, last, position):
        self.id = id
        self.first = first
        self.last = last
        self.position = position

Let's code our implementation into the "HockeyRoster.py" module...and we are not going to worry about using classes here...let's just make an executable module which contains various functions to implement our logic. You can follow the logic of the implementation by reading the comments by each function.


# HockeyRoster.py
#
# Implemenatation logic for the HockeyRoster application

# Import Player class from the Player module
from Player import Player

# Define a list to hold each of te Player objects
playerList = []

# makeSelection()
#
# Creates a selector for our application.  The function prints output to the 
# command line.  It then takes a parameter as keyboard input at the command line
# in order to choose our application option.

def makeSelection():
    validOptions = [1,2,3,4]
    print "Please chose an option\n"

    selection = raw_input("Press 1 to add a player, 2 to print the roster, 3 to search for a player on the team, 4 to quit: ")
    if selection not in validOptions:
        print "Not a valid option, please try again\n"
        makeSelection()
    elif selection == '1':
        addPlayer()
    elif selection == '2':
        printRoster()
    elif selection == '3':
        searchRoster()
    else:
        print "Thanks for using the HockeyRoster application."

# addPlayer()
#
# Accepts keyboard input to add a player object to the roster list.  This function
# creates a new player object each time it is invoked and appends it to the list.
def addPlayer():
    addNew = 'Y'
    print "Add a player to the roster by providing the following information\n"
    while addNew.upper() == 'Y':
        first = raw_input("First Name: ")
        last = raw_input("Last Name: ")
        position = raw_input("Position: ")
        id = len(playerList)
        player = Player()
        player.create(id, first, last, position)
        playerList.append(player)
        print "Player successfully added to the roster\n"
        addNew = raw_input("Add another? (Y or N)")
    makeSelection()

# printRoster()
#
# Prints the contents of the list to the command line as a report
def printRoster():
    print "====================\n"
    print "Complete Team Roster\n"
    print "======================\n\n"
    for player in playerList:
        print "%s %s - %s" % (player.first, player.last, player.position)
    print "\n"
    print "=== End of Roster ===\n"
    makeSelection()

# searchRoster()
#
# Takes input from the command line for a player's name to search within the
# roster list.  If the player is found in the list then an affirmative message
# is printed.  If not found, then a negative message is printed.
def searchRoster():
    found = False
    print "Enter a player name below to search the team\n"
    first = raw_input("First Name: ")
    last = raw_input("Last Name: ")
    position = None
    for player in playerList:
        if player.first.upper() == first.upper() or player.last.upper() == last.upper():
            found = True
            position = player.position
    if found:
        print '%s %s is in the roster as %s' % (first, last, position)
    else:
        print '%s %s is not in the roster.' % (first, last)
    makeSelection()

# main
#
# This is the application entry point.  It simply prints the applicaion title
# to the command line and then invokes the makeSelection() function.
if '''name''' == "'''main'''":
    print "Hockey Roster Application\n\n"
    makeSelection()

When this simple application is invoked, it accepts input from within the Netbeans output window, or at the command line if run on your terminal. The logic is pretty straight forward: enter a player, list the players, search for a player, or exit the application.


Where To Go From Here

Congratulations, you've completed the introductory tutorial. You should now be familiar enough with Python to begin working with modules and create some basic applications. The next step is to familiarize yourself with the concept of object-oriented programming if you've never worked with it before. You will want to learn the basics of developing Python classes and concepts behind their usage.

In the next tutorial, I plan to develop this application further by creating a persistence module to save our data. We will also learn how to use the Netbeans Python debugger to help us debug our application.

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo