CS101: Introduction to Computers and Computing
CS101: Introduction to Computers and Computing

Introduction To The Python Programming Language

There are 3 parts to this lab:

Part 1: Boot computer into Ubuntu operating system, printout grade sheet, and create folder.

Part 2:  Introduction to Jython programming language through the use of print command, variables, and functions.

Part 3: Check all tasks are complete, email assignment to instructor and self, shut down computer, and staple together and turn in grade sheet and code printouts.

Introduction:
A computer program is a set of instructions for the computer to follow to accomplish a task.  An example of a computer program is Microsoft Word.  When Microsoft Word is running on a computer the computer is executing the Microsoft Word program instructions.  When a program such as Word is running the instructions the computer follows must be in binary form (also called machine language) since a computer can only process zeros and ones. 

Programming is the creation of instructions for computers.  When computers were first invented computer programmers had to write computer programs in machine language (zeros and ones).  This proved to be very difficult since humans do not usually write instructions as a series of zeros and ones.  To make programming easier computer programming languages were invented.  High level programming languages allow computer programmers to write the instructions for the computer using human based language principles such as letters, words, base ten numbers, and mathematical symbols instead of just zeros and ones.  Later, when the instructions are run on a computer, another program turns the instructions written by the programmer into the zeros and ones needed by the computer. 

Lab Directions:

Part 1: Boot computer into Ubuntu operating system and printout grade sheet.
When you first start your computer it will be running the MacOS operating system and your screen will look like this:

Current Desktop

For our project we will be using the Ubuntu operating system running in a virtualization environment called VMware Fusion.  In a moment we will be starting the VMware Fusion software.  Once VMware Fusion starts running your screen will look like this:

Ubuntu in pause mode.

To unsuspend Ubuntu just click the white arrow in the middle of the screen. Once Ubuntu is
unsuspend then on the left side of the screen click on the Firefox web browser icon as shown below ...

Click the Firefox icon.

... and once the web browser is running reopen these directions.

To start the software running click on the dock icon called VMware Fusion shown below:


Fusion Icon


Once your computer is running Ubuntu and you have opened today's lab directions in Firefox your screen should similar to the one below:

Drag the
                    lab directions window to the right side of the                    Desktop.

To setup your computer to work more efficiently drag the directions to right side of the screen as shown below:

move directions to
                    right side of screen

For this lab, and each of the remaining labs that require you to complete a project, there will be a grade sheet.  The grade sheet informs you of the tasks you are required to complete in that day's lab and how many points each of the tasks are worth towards the 100 points available for the project.

You are about to download and open the
Python1GradeSheet.xls spreadsheet file using LibreOffice Calc.  When it opens in Calc your screen will look like this:

 Type your
                    name in cell B1 and lab section number in celll f1.

To download today's grade sheet click on the following link: 


In the now open spreadsheet click in cell B1, type your name, and press return on your keyboard.  Next click in cell H1, type your lab section number, and press the return key on your keyboard.   The spreadsheet should now contain your name and lab section number similar to the spreadsheet below:

Type your name in cell
                    B1 and lab section number in celll f1.

Now click once on the grade sheet window to make Calc the active program. 
At the top of the Calc window  select File menu > Print as shown below...

file
                    menu print

... to open the following dialog box:


print box


Select either the By Cabinet or the By Door printer and then click on the OK button.

Now walk up to the printer you selected and place one piece of paper at a time into the manual feed tray and retrieve your printout of the grade sheet.

Close the grade sheet by clicking the red close window button in the upper left corner of the window as shown below...

click red button

... and when the following dialog box appears...

click the don't
                    save button


... select Close without saving.


Your screen should now look like this:

Drag the lab
                      directions window to the right side of the                      Desktop.

Look over grade sheet printout to find the requirements for today's lab.  If you have any questions about the grading ask your instructor. Later in lab we will need to save several items that need to turned in for grading so we will need to create a folder on the desktop.  Right click on the Desktop next to the Firefox icon on the Launcher and from the menu that appears select New Folder as shown below to create a folder on the Ubuntu desktop:

Create a folder on the
                    desktop by right clicking.

A new untitled folder will appear on the desktop as shown below:

new untitled folder on
                    desktop

Ubuntu computers make new folders with the name untitled folder.  Since untitled folder is already highlighted you can replace untitled folder with the name you desire by just starting to type the new name (if your folders name accidentally becomes not highlighted just right click on the the folder and select Rename).  Use the following format for naming the folder: 

lastname_firstinitial_Python1

(i.e. John Smith would call his folder smith_j_Python1)


When done your folder should look like this (with of course your own name):

Folder named first name
                    last name first intial.

When done your computer screen should look similar to this:

just directions

Part 2: Introduction to Jython Programming Language through the use of print command, variables, and functions.
During the first three programming labs you have constructed Alice worlds and you did so without having to type any programming code.  We instead just dragged and dropped instructions into place.  This is the beauty of Alice.  It allows you to learn about programming concepts (such as looping) without having to learn a programming language at the same time.  The downside of using Alice is that you do not get to learn about programming in a more typical programming environment creating a more typical computer program. 

The programming language that we’re using in this lab is Python (visit http://www.python.org for more information on it). Python is a fairly popular programming language, used very often for Web and media programming. The Web search engine Google uses Python. The media company Industrial Light & Magic also uses Python. A list of companies using Python is available at http://wiki.python.org/moin/OrganizationsUsingPython. Python is easy to learn, easy to read, and very flexible.

The version of Python used for this lab is called Jython (http://www.jython.org). Python is normally implemented in the programming language C. Jython is Python implemented in a programming language called Java— this means that Jython is actually a program written in Java. Jython lets us do multimedia that will work across multiple computer platforms. Jython is a real programming language that can be used for serious work. You can download a version of Jython for your computer from the Jython Web site that will work for all kinds of purposes. We will be using Jython in this lab through a special programming environment called JES (Jython Environment for Students) that has been developed to make it easier to program in Jython. But anything you can do in JES, you can also do in normal Jython— and most programs that you write in Jython will also work in Python.  JES is available for Windows, Ubuntu, and Linux. (You can read the instructions on installing JES at http://mediacomputation.org.) 

To start JES find the following icon on the Launcher at the left of the screen...

python icon

... and click once.

Once JES starts running it will look like this:

jes start screen

Move and re-size the Jython window so your screen looks like this:

jes window moved into place

You now have opened the JES programming environment.  The JES window is divided into two areas. 

1) The top part is the Program Area. This is where you will later write your programs. This area is simply a text editor— think of it as Microsoft Word for your programs.

2) The bottom part is the Command Area. This is where you literally command the computer to do something. The commands you give the computer need to be commands that the Jython programming language and/or environment understands.  The computer will interpret your commands and do what you have told it to do.

You can re-size these two areas to better fit your needs. 

We will be using the Command Area more to start with so place your mouse on the dotted gray bar separating the Command Area from the Programming Area and drag the the gray dotted bar near the top of the Jython window so the two areas now look similar in size to screen shot below:

resized work
                  area

If we are going write programs for the computer we need to know exactly what a programming language is.  We all ready know from lecture that the only instructions a computer can really understand are 0's and 1's.  We call this language machine language.  We also know that it is very hard for humans to write instructions for computers in machine language.  Program languages were developed so that humans could write instructions for computers using language and concepts we are more familiar with such as words, base 10 numbers, and mathematical operations.  Later, another program (a compiler or interpreter) looks at the instructions created in a program language by a human and turns them into machine language so the computer can run the instructions.

Computer Science Idea: Program languages are for people not computers.

Much of programming is about naming. Obviously, the computer itself does not care about names. Names are for humans. Since we learned in lecture that a computer can really only do addition, subtraction, multiplication, division, and logically compare numbers, then remembering words and their association with values is just a waste of time for a computer. But for humans naming things is very powerful. It allows us to work with the computer in a natural way. A programming language is really a set of names that a computer has encoded.  We can then use these names to give the computer instructions.  Our instructions will be in the Jython programming language. Later, these instructions written in the Jython language can be turned into the machine language a computer needs.

Remember that names are only meaningful for people, not for computers.

LEARNING TO USE PRINT COMMAND:
The Command Area is a great place to start learning about Jython's particular names and meanings.  We’re going to start out by simply typing commands in the Command Area.  We will not yet be defining new names but simply using the names that the computer already knows from within JES. The name print is an important one to know. It’s always used with something following it. The meaning for print is “ Display a readable representation of whatever follows.”

Click once in the black Command Area to make it active and notice that the Command Area prompt is displayed and looks like this:

command prompt

The three arrows representing the command prompt is Jython's way of telling you that it is ready for you to type in a command.  After the three arrows (prompt) type...

type print 1 + @

... the prompt and what you just typed together should now look like this...

type print 1 + @

...press the return key.  Your Command Area should now look like this:

print 1 + 2

Notice that Jython added the two numbers together and showed you the result of 3.  That is because print is a name that Jython understands. 1 + 2 is a numeric expression that Jython also understands. It is composed of two numbers and an operation '+' that Jython knows how to do, which is add. The print name combines with the numeric expression 1 + 2 to instruct Jython that we would like it to show us the result.  It executes the instruction and shows us the result which is the number 3.

Since using the Command Area is a new experience for most student's let's learn a few important things before we continue:

Command Area Concept #1: When using the Command Area you will make mistakes and the Command Area  will unceremoniously inform you of these mistakes. 
If you enter a command into the Command Area incorrectly the Command Area will let you know by giving you a message.  To see how this works let's issue a command Jython does not understand.  Click in Command Area to make it active and then type in the words not really a command as shown below...

type not really a command

..and then press the return key on the keyboard to enter the unknown command to Jython.  Since the command is not known by Jython you will get the following message:

command not found message is
                  displayed

The message is Jython's way of informing you that it does not understand the command issued.  Syntax means the rules for a language.  A syntax error means we have violated a rule, or rules, for the Jython language.  The Command Area then automatically puts up another command prompt so you could try again.  This means that if you do make an error typing in a command during today's lab do not worry.  As long as the command prompt the command prompt reappears you can just try entering the command again.

Command Area Concept #2: The Command Area does NOT function like a word processor .
One reaction by users new to the Command Area after they issue a bad command is to try and 'delete' the command and try again.  To do this they use their mouse to click after the text of the command (in our case the text was not really a command) with the thought that they will position the cursor and then press the delete key to delete text of the bad command.  Try this technique, or any other you usually use to delete text in a word processor (except closing the Window), to delete our bad command and you will find that the text is there to stay.  

It is easy to see why someone would think the Command Area would behave like a word processing program because they look similar.  However, they perform very different functions.  Just think of any text above your current command prompt as a history of your Command Area session, and you cannot change history.

Command Area Concept #3: If you close a JES window you will lose the text displaying your history of commands.
Go ahead and close the JES window by clicking the red button in the upper left corner of the window.  Then reopen the JES by clicking again in its icon on the Launcher.  Once the JES starts running again setup your work area as shown below:

jes window moved into place

Notice that our previous commands are now gone.  During the next part of today’s lab, try not to close your JES window since being able to see what you have done may be helpful in trying to correct any problems you have.

We now have one name that Jython understands: print.  Let's see what else we can do with the print command and what other kinds of mathematical expressions Jython understands.

At the command prompt type ...

type print
                15 - 14

... and press the return key.  Your Command Area should now look like this:

33+11

You already know that Jython knows how to perform addition.  However, your instructor needs to know you know.  The problem is that when we close JES all your commands and results will disappear.  Fear not, we will use the Ubuntu built in screen capture capabilities to capture and save your answers.  

Follow the directions in the screen shot below to capture the information you just produced in the Command Area...

how to capture screen

... after you capture your screen shot you will be presented with the dialog box shown below...

textedit
                  window

... click on Save to save the screen shot to the Pictures folder.

Your screen should now look like this:

current desktop

Whenever you need to capture your your Command Area work as a screen shot just repeat the above steps.

Now on the grade sheet you printed out at the beginning of lab, locate Question 1 as shown below...

 'Question 1 has correct screen shot in Picture's folder and the value is ______ '

...and in the blank write the output of  print 15-14, which was the value of 1.

Now using this same process as earlier (type command into Command Area, save screen shot of completed commands in Pictures folder, and write the output value of completed command in blank on grade sheet) show what the output is for the following print commands:

Question 2:   print 22*33
Question 3:   print 34.1/45.5
Question 4:   print 1+2+3+4+5
Question 5:   print 10+3*7
Question 6:   print (10+3)*7

Jython also knows how to recognize text strings. Text strings are sequences of characters that are started and ended with quote marks (for example 'this is a text string').  Using this same process as earlier (type command into Command Area, save screen shot of completed command in Pictures folder, and write the output value of completed command in blank on grade sheet) show what the output is for the following print commands:

Question 7:     print 'hello'
Question 8:   print  'bye'

Jython even knows what it means to “add” two strings together: it simply puts one right after the other.  Using this same process as earlier (type command into Command Area, save screen shot of completed command in Pictures folder, and write the output value of completed command in blank on grade sheet) show what the output is for the following print commands:

Question 9:   print 'hello ' + 'there'

As you can see Jython understands the name print.

CREATING YOUR OWN NAMES AND VALUES USING VARIABLES:
In our last programming lab we made a countdown timer for our Crazy Cube car game.  When creating the game we needed a place in the computer's memory that would keep track of how much time was left on the timer.  We told Alice that the place in memory that would keep track of the time would be called countdown timer. As the timer ran during the game the computer was able to change the value of countdown timer as the program counted down from 10 seconds to 0 seconds.  When we create a place in the computer's memory where values can be stored, and changed, we call this creating a variable.  It is a variable because the value stored in the computer memory can change when needed.

Jython, like almost all programming languages, has the ability to create these places in a computer's memory called variables.  Let's say we needed to store the value of 12 in the computer's memory.  To accomplish this type the following command in the Command Area:

type into command area

Jython just created a place in the computer's memory called myVariable and stored the value of 12 in that location.  However, at this point we are just taking the computer's word that it created the variable and stored the value.  How can we check if the computer accomplished this or not?  We can use a print command.  In the Command Area type...

type into command area

... and press the return key.  The value of 12, currently stored in the computers memory under the name myVariable, was printed as shown below:

12 is displayed

Now we know for sure there is a place in the computers memory called myVariable and the value of 12 is stored at that location.

Here is an important rule for variables:  Don’t read the '=' sign as 'equals.' That’s what it means in mathematics, but that’s not at all what we’re doing here. Read the '=' sign as 'becomes a name for'.  Remember programming languages are all about putting names on values to make programming easier for humans.  myVariable = 12 thus means 'myVariable becomes a name for 12.'

We will now create a second spot in the computers memory called anotherVariable and store the value of 3 at this new location by typing in the following command:

type in
                command area

To check the variable exists in the computer's memory with the correct value type the following print command...

type
                command

... and press the return key.  3 should have printed as the value as shown below:

3 displayed

We now have two variables stored in the computers memory.  We can now use the values stored in these two locations in the computer's memory in other tasks.  To demonstrate, type the following in the Command Area...

value of 15
                displayed

... and then press the return key.  The following should have printed:

the value of
                15 displayed

The above command resulted in the output of 15.  That is because the computer pulls the value stored at each of the variables locations in memory (myVariable = 12 and anotherVariable = 3) and adds the values together (12 + 3).

Using this same process we used earlier in the lab (type command into Command Area, save screen shot of completed command in Pictures folder, and write the output value of completed command in blank on grade sheet) show what the output is for the following print commands:

Question 10:   print myVariable / anotherVariable
Question 11:   print myVariable - anotherVariable

We can change the value of a variable stored in memory whenever needed.  This is a very important concept in programming.  To demonstrate type the following in the Command Area...

type value of 100

... and the press the return key.  Now enter in the command...

type print
                command

... and press the return key.  The following value should have printed:

the value of
                100 returned

Notice that the print command returns the value of 100 and not the value of 12 that used to be stored at the location in memory called myVariable.  We have now changed the value of the variable called myVariable from 12 to 100.

Using this same process we used earlier (type command into Command Area, save screen shot of completed command in Pictures folder, and write the output value of completed command in blank on grade sheet) show what the output is for the following print commands:

Question 12:  print myVariable / anotherVariable
Question 13:  print myVariable - anotherVariable

Variables can store different types of values besides numeric.  We can also store a text string in a variable.  Remember that a text string is a set of characters enclosed in parentheses such as, 'hello'.  Let's change the value of our two variables from numeric values to text string values.  In the Command Area type the following...

type hello

... and press the return key.  Then type at the command prompt...

enter
                myvariable = hello

... and press the return key.  The following value should have printed:

hello
                returned value

We have now changed the value of myVariable three times.  First the value stored in the computers memory was 12, then we changed it to 100, and just now we changed it to the text string hello

At the command prompt type the following...

type hello

... and press the return key.  Then type at the command prompt...

enter
                myvariable = hello

... and press the return key.  The following value should have printed:

hello
                returned value

Using this same process we used earlier in lab (type command into Command Area, save screen shot of completed command in Pictures folder, and write the output value of completed command in blank on grade sheet) show what the output is for the following print command:

Question 14:  print myVariable + anotherVariable

Let's practice creating variables.  Remember that what is to the left of the = sign will become the name for the variable.  What is to the right of the = sign will become the value of the variable.  Using this same process we used earlier in lab (type command into Command Area, save screen shot of completed command in Pictures folder, and write the output value of completed command in blank on grade sheet) show what the output is for the following print commands:

Question 15:
myVariable = 3
anotherVariable = 4
print
myVariable + anotherVariable

Question 16 (IMPORTANT NOTE: WE DO NOT USE myVariable or anotherVariable AS THE NAMED PLACES IN MEMORY ANYMORE.) :
a = 5
b = 3
print a + b


Question 17:
a = 5
b = -3
print a + b


Question 18:
a = 5
b = -3
x = a + b
print x


Question 19:
number = 1
number = 2
print number


Question 20:
name = 'Sue'
name = 'Jane'
print name


Question 21:
sueName = 'Sue'
janeName = 'Jane'
print sueName + janeName

Question 22:
name = 1
name = 'Jane'
print name


If you have any questions about creating variables and/or changing a variables value ask your instructor for help before continuing with these directions.

Now we know two important things about Jython: 

1) The print command displays what follows the command.

2) Variables are used to store values in the computers memory.  Variables have names and the names represent a value in the computers memory.  The print command can be used to see what the computer has stored currently for the value of a variable.

USING FUNCTIONS IN JYTHON:
Our third concept we will learn about Jython is the use of functions.

In Alice we used a function to test 'is the car within 1 meter of the cube' while the Crazy Cube game was running.  The function took in the value of the current location of the car relative to the cube and returned a value of either true (is the car within 1 meter of the cube) or false (is the car is not within 1 meter of the cube).

In Jython, functions can also take in a value and return a value.  A function already built into Jython is the square root function.  The square root function takes in the value of a number and returns the value of the square root of the number.  Let's give it a try by calling the square root function (when you ask Jython to run a function you are 'calling' the function.)

In the Command Area type print followed by the square root function call as shown below...

type
                absolute -2

... and then press the return key.   The following should be the output:

the output

Notice that the square root function took in the value of 4 and returned the value of 2.0

When we called the square root function we passed the square root function the value of 4.   Since 4 was passed to the function as a value we can call the 4 a parameter.  When we pass values to functions we call these inputs parameters.  Parameters passed to a function in Jython are always enclosed by parentheses.  That is why the function call of sqrt was followed by the parameter of four in parentheses sqrt(4).

Using this same process we used earlier in lab (type command into Command Area, save screen shot of completed command in Pictures folder, and write the output value of completed command in blank on grade sheet) show what the output is for the following square root function calls passed the respective parameters:

Question 23: print sqrt(9)
Question 24: print sqrt(25)

What would happen if we call the square root function and pass to it no value as its parameter?  This time let's pass the square root function no value as its parameter.  To accomplish this we will type in no value between the parentheses.  At the command prompt type the following command.....

abs function
                with no value

... and then press the return key. As you can see we have an error message.  This makes sense as it is impossible to find a square root of a number if you are not given a number first.  Since the function was not passed a numeric value as a parameter we get the following error message:

error
                message

Any function that expects its parameter to contain a value when called will give you an error message if you do not pass it a value. 

What would happen if we call a function and pass to it the wrong kind of value as its parameter?  Instead of passing a numeric value as the parameter to the square root function we will instead pass it a text string (remember that a text string is characters surrounded by quotes such as, 'hello').  At the command prompt type the following command...

pass square
                root text string

... and press the return key.  Jython will give you the following error message:

error
                messge

Any function that expects its parameter to contain a certain type of value when called will give you this error message if you do not pass it the correct type of value.

Using this same process we used earlier in lab (type command into Command Area, save screen shot of completed command in Pictures folder, and write the output value of completed command in blank on grade sheet) show what the output is for the following square root function call passed the parameter of 16:

Question 25: print sqrt(16)

In Question 31 above the square root function was passed the value of 16 as its parameter.  We already know we can store values in the computer's memory as variables.  Can values stored in variables be passed to a function as a parameter?  They sure can.  Let's demonstrate by storing the value of 16 in a variable and then using the variables name as the parameter for the square root function.  At the command prompt enter the following command:

set number
                to 16

Jython just created a place in the computer's memory called number and stored the value of 16 in that location.    Let's see if you can pass this value to the square root function as its parameter with the following command:

number to
                square root

You should see the following output returned from the square root function:

output from
                function

Since the word number represented the value 16 in the computers memory, the square root function was really passed the value of 16.  The square root of 16 is 4.

Let's change the value of the variable number and see if we can pass the new value as the parameter to the square root function by entering the following command:

change
                number to25

Let's call the square root function again and see if the new value of number was passed as the parameter by typing...

square root
                function

... and after pressing the return key getting the following output from the function:

new output

You have just learned a very important and powerful programming concept:

THE VALUE STORED IN A VARIABLE CAN BE PASSED TO A FUNCTION AS AN INPUT VALUE (PARAMETER)!

Let's try this important concept a few more times by using this same process we used earlier in lab (type command into Command Area, save screen shot of completed command in Pictures folder, and write the output value of completed command in blank on grade sheet) to show what the output is for the following square root function calls passed the respective parameters as variables:

Question 26:
passedValue = 36
print sqrt(
passedValue)

Question 27:
integerInput = 49
print sqrt(
integerInput)

Question 28:
integerInput = 4
print sqrt(
integerInput)

Question 29:
integerInput = 16
integerInput = 36
print sqrt(integerInput)


We just used Jython's built-in square root function to practice a very important and powerful programming concept:

THE VALUE STORED IN A VARIABLE CAN BE PASSED TO A FUNCTION AS AN INPUT VALUE (PARAMETER)!

To see why this is such a powerful programming tool we will need to learn another of Python's built-in functions: requestInteger. To see how the requestInteger function works type the following command but do not enter the command yet:

type
                function

Notice that in the above command the requestInteger function has an input value (parameter). The input value (parameter) is the following text string:

parameter

Press the return key to enter the command. The requestInteger function knows how to open a dialog box that has the title of Input as shown below (and is highlighted in red for these directions):

Input dialog box

This Input dialog box displays the input value (parameter) (in this case the text string parameter ) as a message in the Input dialog box (and is highlighted in red for these directions):

input text

In the Input dialog box the requestInteger function opens there is an area were the user can enter an integer number (an integer number is a number with no decimal points).  Enter 4 into the dialog box as shown below...

enter 5 into box

.. and then click OK.

In the Command Area the command you just entered will now be followed by the number we just entered into the Input dialog box as shown below:

input

We can see that the output for the requestInteger function is the number the user types into the dialog box, which in this case was 4

Now that we know how both the requestInteger function and sqrt (square root) function work, we can use both of them to demonstrate our very important programming concept:

THE VALUE STORED IN A VARIABLE CAN BE PASSED TO A FUNCTION AS AN INPUT VALUE (PARAMETER)!

We can demonstrate this important concept by taking the value output from the requestInteger function (the number 4 in the above example), store the value (the number 4) as a variable in the computer's memory, and then pass the value (the number 4) to the sqrt function as its input value (the number 4).  This concept is illustrated below in the following diagram:

value
                  diagram

As the above diagram illustrates the output value from the requestInteger function becomes the input value for the sqrt function.  This is what makes the concept...

THE VALUE STORED IN A VARIABLE CAN BE PASSED TO A FUNCTION AS AN INPUT VALUE (PARAMETER)!

...so important.   By using variables to store one function's output, we can pass that output to another function as its input.  This allows functions to communicate with each other by passing values from one function to another. 

Congratulation! You just accomplished a major programming concept.  You now have the very important programming ability to pass information from one function to another!

It would be nice if we could save these commands and run them whenever we needed to calculate the square root of an integer.  Wait, that sounds like a program.  Remember a program is a set of commands for the computer to follow to accomplish a task.  This sounds like the perfect time to create our first program in Jython.

CREATING A PROGRAM IN JYTHON:
A program in Jython is just a function, or a collection of functions, that perform a task.  We have been calling some of Jython's built in functions.  Now we are going to create our own function (program) that will reproduce what our series of commands accomplished earlier, mainly, when called the function will allow the user to input an integer and have its square root calculated.  The advantage of creating our own function is we can save it and use it whenever needed.

To prepare to create our first function (program) close Jython by clicking the red button in the upper left corner and then reopen by clicking the icon on the Launcher on the left of the screen.  Once open again set up your computer to look like this:

jes window moved into place

Notice that by closing JES and reopening the Command Area is now empty.  Once again we see the problem of creating things in the Command Area, they go away when the JES environment is closed. 

We are now going to use the white Program Area in JES.  When we create functions in the Program Area they can be saved, opened, and run whenever they are needed. 

Remember when we said earlier that just about anything can be named in computers?  Now we will name our own function.  Jython calls this defining a function. 

The command that Jython understands as defining the name of new functions is def. In the Program Area type the def command as shown below:

type def into
                  the program area

There are certain things that have to come after the command def so that Jython can understand the instruction. The structure of what goes on the line with the def command is referred to as the syntax of the command.  Remember syntax is the rules of a language (in this case the rules for Jython).  The def command needs three items to have the correct syntax.

ITEM 1) The first item that should follow the def command is the name of the function you’re defining.  We are going to create a function that allows the user to input an integer and have its square root calculated. A good name for the function would be calculateSquareRoot so type that in after the command def as shown below:

type empty parentheses 

ITEM 2) The second item that should follow the def command is the parameter that will be passed to the function.  In this case our function will not have any value passed to it as a parameter, so we can just put a set of empty parentheses as shown below:

type empty parentheses

ITEM 3) The third item that should come after the def command is a colon (not a semi-colon).

type a colon

After we have defined our function we need to enter the commands to be executed when the function is called.  You create a collection of instructions by defining a block. We show which commands are part of the function through the use of indentation. All the statements that are part of the definition are slightly indented after the def statement. It is recommend you use exactly two spaces— it’s enough to see, it’s easy to remember, and it’s simple.  Type in the following instruction making sure to indent two spaces as shown below:

type in commands

You should recognize the first command in our function's block.  It creates a variable called integerInput and then sets the value of integerInput to the integer that user enters and is the value output by the function requestInteger

Next type the following command:

next command


The second command in our function's block calls the function sqrt and passes over as the input value (parameter) the value stored in the variable integerInput.  Since we put a print statement in front of the sqrt function it will then display the value of integerInput in the Command Area.

It you typed the two commands in our calculateSquareRoot function correctly you’ll notice a thin blue box around the body of the function. The blue box indicates the blocks in your program. All the commands in the same block will run when the our function calculateSquareRoot is called.  Our block contains two commands.  When the function is called the two commands will be executed and the user should be able to enter a number into the Input window and see the square root of that number displayed in the Command Area.

We have just defined our first function (program) in Jython.  How do we call our function (run the program).  To make the initial function call takes three steps.

Step 1) We need to save the program to disk.  Select File menu > Save Program as shown below:

select save program

When the Save dialog box opens it will look like this...

save 2

double click on the Desktop folder to display the contents in the dialog box as shown below...

save dialog
                  box

...and then double click on your folder, so that your Save dialog box looks similar to this:

desktop

Lastly, at the bottom of the Save dialog type in the following name...

lastname_firstinitial_calculateSquareRoot
(For example John Smith would use the name: smith_j_calculateSquareRoot)

... and now your Save dialog box should look similar this:

save 1

... and then click on the Save button.

Step 2) We need to load the program into the computer's memory.  In the gray area separating the Program Area from the Command Area click once on the Load Program button as shown below:

click the load
                  button

A message in the Command Area should inform you that the program is now loading into the computer's memory (IMPORTANT NOTE: The Command Area never actually tells you that your program has loaded.  It only takes the computer a fraction of a second to load the program so you can safely continue on while the Loading Program message is displayed.) as shown below:

program loaded

Step 3) We need to call (run) our function.  In the Command Area type the following command to call our new calculateSquareRoot function...

type
                command

... and press the return key.

We just received an error message from Jython when it attempted to call our new function as shown below:

errror
                message

We will have to correct the error before we can successfully call the new function.  Correcting errors in programming is called debugging.  Most of the time a programming environment will attempt to help you located and correct bugs.  In our case Jython is giving us lots of information about the error.  If we look at the first part of the error message...

error
                message

...it is telling us that the function call requestIntegers Name not found globally.  This means that Jython does not recognize the name requestIntegers as a function call. 

Another hint that is given to help us fine the bug is in the actual code you have already typed in the Program Area.  If you look at the code you have typed you will notice that one of the lines is highlighted yellow as shown below:

highlighted error

This is Jython's way of letting you know which part of the code it was unable to compile.  In our case the highlighted line contains the function call buggy function
                call.  If you look closely you will notice we have typed in the function's name incorrectly by adding an 's' to the end of the functions name.  The function's name should be: requestInteger not requestIntegers. To correct the error delete the 's' so that the code now looks like this:

delete the s

Did you notice that when you deleted the 's' that the yellow highlighting of line two disappeared.  It disappeared because Jython does not detect an error in the code anymore.  You may have also noticed that the function name requestInteger turned purple when you corrected the error.  Most program languages help you by color coding the instructions as you enter them into the editor.  In this case the function name turning purple is Jython's way of letting you know that it now recognizes the name requestInteger as a function's name.  You might notice that the other function in our code, sqrt, is also purple.

We have corrected the bug so we will need to re-save our code by selecting File menu > Save as shown below:

resave your code

Then reload your code by selecting the Load Program button as shown below:

click the load
                  button


Let's try calling our new calculateSquareRoot function again by typing the following command...

type
                command

... and pressing the return key (If you have any more bugs make sure to correct the bug, save your program, and reload the program before continuing.)

When our new function is called with the above command it will first display the Input dialog box as shown below:

dialog box


Enter 4 into the dialog box as shown below...

enter 5 into box

.. and then click OK.

In the Command Area the function call you just entered will now be followed by the square root of the number (the square root of 4 is 2.0) we just entered into the Input dialog box as shown below:

input

Congratulations! You just ran your first Jython program by issuing a calculateSquareRoot() function call.  Since the instructions for our program are saved we could run the program anytime we needed to without having to retype all the commands.  Go ahead and call the function again using the command...

type
                command

.. and try inputting the integer value your own choice.  Then try running the function a few other times inputting different integer values.

Let's take a look at how our function calculateSquareRoot executed when it was called:

function call


The calculateSquareRoot function executes the first command in its block as shown below

first command

After the first command in the block is executed the second command is executed as shown below:

second command

One problem you may have noticed with our program is the output:

input

It not very descriptive. It would be nicer if we could give the user a message like:

The square root of 4 is 2.0

When you were working in the Command Area in the first part of the lab you learned you can store a string of text in a variable like the example below:

name = 'Sue'
name = 'Jane'
print name


We will now add a text string to our output.  Add the following line to your function:

Add line to code

Now Save your program, reload, and issue the calculateSquareRoot() command to run your function.  Notice how the text in double quotes after the print command is output exactly as it was typed as shown below:

text output

We now need to add in the number the user wanted to find the square root of and the square root of that number to the output.  The number the user wants to find the square root of is stored in the computers memory at integerInput.  We can add this number to our output by using a formatter.  Add a %s to the last line of your function as shown below:

add %s

This formatter tells the function you want to pull a value from memory and place it in the text string at that spot.  We now need to tell the function we want to place the number stored at integerInput at that spot.  We do this by adding the following to the end of the last line of the program as shown below:

add the following 

The % sign tells the program that what will follow in parenthesis is the places in memory you would like to pull the information from and add to the text string at the spot marked by the %s. 

Save your program, reload, and issue the calculateSquareRoot() command to run your function and you should see the following output:

the new output 

Notice how the the function replaced the %s with the number stored at integerInput.  We now just need to add the square root of that number to the output.  First add another %s to the text string as shown below:

add another s%

Now we need to tell the function where in memory to find the information to put in place of the %s.  Add the following to the parenthesis at the end of the last line as shown below:

add the following

What we just added to our function will have the sqrt function go to the spot memory call integerInput and calculate the square root of the number stored there, it will they display that number in place of the second %s.

Save your program, reload, and issue the calculateSquareRoot() command to run your function and you should see the following output:

output

Now that we have better output from our program we actually do not need the third line of our function.  Delete the third line so that the function looks like the one shown below:

delete the third line

Save your program, reload, and issue the calculateSquareRoot() command to make sure your function still runs correctly.

We have one more task to complete in our program.  Part of programming is documenting your program.  Documenting your program means placing comments in the program that explain what it is the program code is doing.  Comments are not for the computer to run they are for other programmers to read so they can better understand what the program is doing.  We will place a comment in the program that documents who made the program and what it does.  Comments are proceeded by a number sign (#), which tells the computer that the line is a comment and not an instruction for the program.  In the Program Area click once at the beginning of the code and type the following comment lines (adding the today's date, your actual name, and your actual lab section number in the correct places) as shown below:

add the comments below

Notice that the comment lines turned green.  This is Jython's way of telling us that these lines are comments and not part of the program. 

Select File menu > Save to save your code.

Extra Credit: For 20 extra credit points add one more print command line to your function.  Using the same type of formatted print command we just learned about have the new print command calculate the square of the number entered and have your program produce the following output for any number entered by the user.

output


Select File menu > Save to save your code as shown below:

save program

We will now printout your program for grading.  Select File menu > Print as shown below...

print program

... when the Print dialog box appear select either By Cabinet or  By Door as your printer as shown below...

select printer

... click the Page Setup tab and select Landscape as shown below...

select landscape

...and then click on the Print button.

That is all the programming we will be doing today.

It is very important you now exit the JES program by making the JES window active and then selecting the File menu > Exit as shown below:

exit program

Part 3: Check all tasks are complete, email assignment to instructor and self, shut down computer, and staple together and turn in grade sheet and code printouts.
Your desktop should now look like this:

just directions

We now have to copy your screen shots to your assignment folder. Click once once on the file cabinet icon at the top of the Launcher on the left side of our screen as shown below:

file
                  cabinet

A window will open showing the Home directory as shown below:

student directory

We will now open the Pictures folder to check in contains your screen shoots. Double click on the folder called Pictures as shown below....

open
                  pictures

...it should contain your screen shots and look similar to the window below (if your window does not look similar ask your instructor for help):

open
                  pictures

If your screen shots are in the folder click the windows back button as shown below:

click the back button

Now right click on the Pictures folder and select Copy To... as shown below:

select copy

When the Select Destination window opens...

select desktop

... double click on Desktop to open the directory as shown below:

select desktop

Now double click on your folder as shown below:

select your folder

After double clicking on your folder to select it then click on the Select button as shown below:

click select

The Pictures folder containing your screen shots should now be copied to your folder.

Now close the Home directory window and your desktop should look like this:

just directions

Open your folder on the desktop by double clicking.   When your folder opens make sure it contains the following 4 items shown below:

check the
                    contents of your folder

If you are missing any items ask your instructor for help.  Close the window containing your folder items.

Now look over your grade sheet to make sure you have completed all items.  If you are unsure of any of the steps ask your instructor for help.

Your screen should look similar to this:

just
                        directions


Next we will compress a copy of your folder so that we can email it to both yourself as a backup and to your instructor for grading. Right click on our folder and select Compress... as shown below:

compress your folder

Make sure that the dialog box that appears is setup similar to the one shown below...

click create

... and then click on Create. A confirmation box will open as shown below...

click ok

... click Close.

A compress version of your folder and files will show up on the desktop as shown below:

compressed file

Follow the steps below to send the new compressed folder to yourself and your instructor:

Step 1) Click the following link to open the SSU login page, in a new tab, to login to your online SSU email account (or other online email account).

Step 2) Create a new email.

Step 3) Fill in the subject for the email as:

lastname_firstinitial_Python1
(example: smith_j_Python1)

Step 4) Attach the compressed folder to the new email.

Step 5) Address the email to your instructor's email address (highlight and copy the email address for your instructor from the list below):

Mr. Carter's lab section's use this email address = cs101carter@cs.sonoma.edu

Mr. Caruso's lab section's use this email address = carusor@sonoma.edu

Step 6) CC the email to yourself.

Step 7) Send the email.

Once you have emailed in your assignment make sure you have your two printouts. You will turn these into your instructor with the grade sheet stapled to the top.

Lastly, to exit out of Ubuntu running in VMware Fusion and shut down the computer place your mouse at the top of the screen and wait until the VMware Fusion menus appear and then select Apple menu > Shut Down... as shown below...
Select shut down.

... and when the following dialog box appears select Shut Down as shown below:

Select Shut Down

End of Lab.