How to Program, Part I

This is to be a very basic tutorial in how to program, designed for the complete novice. It will be based on Python, because that language is:

  1. Free (you can get it from here)
  2. Has a simple and uncluttered syntax.
  3. Runs on virtually all computers.
  4. Makes it easier to introduce concepts one at a time.
Go to the C:\Python25 directory to run programs from the command line. Use either "write" or "notepad" to create text files. Note that if you create a file with notepad choose "All Files" as the type. Here we see an example of someone running the "hello" program illustrated below. Notepad remains open so that you can edit the program.

As an illustration of this last point, consider your python program:

file: hello.py
1 print "hello"
> python hello.py
hello

This is a complete program that will execute on any computer.

All the examples in this tutorial will be formatted in the above fashion. We show the file name in the blue header, the code listing with line numbers below it, and an execution of the file below that using white text on a black background.

This program shows you how to use the print statement. You can tell python to print any words you want, and it will. Try it!

Now let's look at your second program:

file: hellox.py
1 x = "hello"
2 print x,x
> python hellox.py
hello hello

Here you assign a variable. We set x equal to "hello" and then are able to use it in print statements.

The bit of text inside the quotations is commonly called a "string." Thus, we say that x is a string variable. We could have used single quotes instead of double quotes, and the program would work the same way.

If we want, we can add "comments" to the code. Comments are pieces of text which do not affect the execution of a program, but does help humans to understand the code better.

Here is an example of the use of comments:

file: helloc.py
1 # the variable x contains a greeting
2 x = "hello" # I should remember change this to aloha for the Hawaiian version
3 
4 print x,x
> python helloc.py
hello hello

For our third program, let's make a small calculator:

file: shopping.py
1 gallon_milk = 3.89
2 loaf_bread = 1.50
3 box_cereal = 2.50
4 groceries = 3*gallon_milk + 2*loaf_bread + 5*box_cereal
5 print groceries
> python shopping.py
27.17

This program prints the cost of our groceries. Now let's add sales tax.

file: shoptax.py
1 gallon_milk = 3.89
2 loaf_bread = 1.50
3 box_cereal = 2.50
4 groceries = 3*gallon_milk + 2*loaf_bread + 5*box_cereal
5 tax = 0.06 * groceries
6 total = groceries + tax
7 print "groceries=",groceries,"/tax=",tax,"/total=",total
> python shoptax.py
groceries= 27.17 /tax= 1.6302 /total= 28.8002

Obviously this program is not rounding to the nearest cent -- but we won't explain how to do that just yet. Already you have learned how to do something useful with Python! You can use it as a calculator.