Overview

Python is a programming language, and also the software that you need in order to use the language. It comes with an "Integrated Development Environment" or "IDE" called IDLE, which can be used both interactively and to build and run programs from source files.

This tutorial shows some basics about using Python by way of IDLE. It is targeted at non-programmers, and tries to take easy, baby steps at first. Some of the concepts introduced are:

Tutorial

  1. Getting the software.

    For this tutorial you need the Python package itself, and two additional modules called "Visual Python" and "Numeric". These are included (along with other modules) in the setup-Python SFX portable package. You can download and run this file — accept the default "installation" directory or choose one that you prefer.

    The original packages can be installed on your own computer and can be obtained from:

  2. Start up.

    Start the IDLE program that comes with Python. If you used the "setup-Python SFX" then look in its directory and double-click the go_IDLE.cmd item. If you installed the original packages then you should have an icon entry in your "Start" menu and possibly on your desktop.

    IDLE is a Python's built-in "Integrated Development Environment" or "IDE". It may start with a "Python Shell" that looks like the screen on the left, or an "Untitled" editor like on the right. If the shell opens, you're in the Interactive window. If the editor opens, you can get to the Interactive window by clicking the RunPythonShell menu item.

    Interactive Shell windowEditor windowRun menu
    shell window editor window run menu
  3. Interactive use.

    At the command prompt, type in a simple arithmetic formula and press the "Enter" key:
    6 + 7
    Python evaluates the expression and shows the answer:
    13
    Important: Don't put a space in front of your expression! You'll get an error if you do!
      6 + 7
    IndentationError: unexpected indent

    All the basic arithmetic operations are supported:
    + addition      * multiplication      / division
    - subtraction      ** exponentiation ("raise to a power")      % remainder (modulus)
    6 - 7
    -1
    6 * 7
    42
    10 / 2
    5
    7 % 4
    3
    2 ** 3
    8
    10 ** 2
    100
    16 ** 0.5 # same as taking the square root...
    4.0
    2 ** -1 # same as finding the inverse...
    0.5

    Integers versus decimals: If your formula only uses integers (whole numbers), the answer will only use integers (except with the ** operator). If you want a decimal answer, you have to use numbers with decimals — even if the decimal portion is just 0. Try these examples, and look at your outputs:

    6.0 + 7
    13.0
    7.0 / 4.0
    1.75
    7 / 4
    1

    Parenthesized expressions: As in any algebraic expression, you can use parentheses to indicate which parts should be calculated first:

    5 + 8 / 3 - 5 # remember — integer division!
    2
    (5 + 8) / (3 - 5)
    -7
    (5 + 8) / (3 - 5)
    -6.5
  4. More math.

    Beyond simple arithmetic operators, Python offers advanced math functions. To use them, first import the math module. Then use the function you want in an expression. You can get some basic help to show you what's provided.
    import math
     
    math.log(8, 2)
    3
    math.log(100, 10)
    2
    math.log10(100) # ...because logarithm to base 10 is very common...
    2
    math.sin(math.radians(90))
    1.0
    math.pi
    3.1415926535897931
    help(math)
    ...you'll see a listing of what the math module provides...
  5. Text strings.

    Text strings are any group of characters that are enclosed in quotes. Either single quotes (') or double quotes (") may be used; this is helpful if a quote mark is supposed to be part of the string.

    What can you do with strings? Well, you can concatenate them (join them together):
    'Alice' + 'Bob'
    'AliceBob'
    'Alice' + ' ' + 'Bob'
    'Alice Bob'
    "Carol is" + " Dave's friend." # notice the apostrophe / single-quote
    "Carol is Dave's friend."


    You can repeat them:
    'banana' * 3
    'bananabananabanana'


    You can measure them:
    len('banana')
    6

    Other operations are shown in the string operations appendix below.

  6. Variables.

    Numbers and text strings are constants — whatever value they have, that's what they are. But most programs need to operate on values that change. For this we need variables, which are named "containers" that can hold constants, the results of calculations, or any other value.

    You create a variable by choosing a name and assigning a value to it. The name must begin with a letter, and can contain letters, digits, and the "underscore" character (the "_"). Uppercase and lowercase letters are different. It is generally a good idea to use a variable name that reflects what the variable is used for.
    count = 7
    7
    fruit = 'banana'
    'banana'
    bananas = 'banana' * 3
    'bananabananabanana'
    bunch = fruit + ' ' + bananas
    'banana bananabananabanana'

    Notice the difference between a variable's name, and a text string:
    • 'banana', in quotes, is a text string, and anthing can go inside the quotes; but
    • banana without quotes is treated as the name of a variable — and if you haven't yet created a variable with this name (or misspelled the name) you'll get an error that the name (shown in quotes) "is not defined".
    fruit
    'banana'
    frut
    NameError: name 'frut' is not defined
    Always pay attention to your spelling!
  7. Objects; Visual Python.

    Numbers and text strings are fairly simple objects, with properties that are fairly easy to guess. Python also provides more elaborate objects, each with properties suited to its use. Many of these objects are defined by additional modules, similar to the math module seen earlier.

    The visual module defines three-dimensional graphical objects, and properties to use with them. Here is a smallish example:
    import visual
    xAx = visual.arrow(axis=(10,0,0), shaftwidth=0.1)
    yAx = visual.arrow(axis=(0,10,0), shaftwidth=0.1)
    zAx = visual.arrow(axis=(0,0,10), shaftwidth=0.1)
    xAx.color = visual.color.red
    yAx.color = visual.color.green
    You should open up a window that looks like the Figure: Axes.

    The initial view is looking straight down the X axis, so you don't really see the third arrow. But you can right-click and hold the mouse in the window, and drag it around to rotate the view. Figure: Axes rotated shows the same window, rotated slightly to show all three arrows.

    The visual module defines a number of other objects as well. Here are a couple more, added to the picture in different positions. Figure: Box and Ball shows the result.

    box1 = visual.box(pos=(1,7,9), color=(1,1,0))
    ball1 = visual.sphere(pos=(7,0.5,3), color=(0,0,1))

    An object's properties can be assigned values when the object is first created, or later on (or both). The arrows got their pos and shaftwidth properties to start with, and the colors were added afterwards; the ball and box get their properties — pos and color — right from the start. It's just a matter of convenience.

    axes1
    Figure: Axes rotated
    box-ball
    Figure: Box and Ball
  8. Programs in files.

    Typing all these commands directly into Python is fine for "trying it out", but everything goes away as soon as Python ends. Programs are created typing all the commands into a file, and then running the file to execute everything at once.

    First open a Python editor window: click on the FileNew Window menu item. Then type in the commands shown previously in the Objects; Visual Python step. Figure: Box-Ball program shows the Box-and-Ball commands saved as a program, with some comments added.

    Programmers generally "document" their programs by adding comments to the file. Python comments always start with the # symbol; anything that follows # on that line is ignored.

    Once the program is created, the file must be saved; it must have a name that ends in .py in order for Python to recognize it. Then run the program by clicking on the RunRun Module menu item. This is shown in Figure: Run Module. The result should look identical to Figure: Box and Ball.

    run menu
    Figure: Run Module
    box-ball
    Figure: Box and Ball again
  9. Some animation.

References

Here are some other tutorials on Python, gleaned from a quick Web search. These may be more detailed, and presume more familiarity with programming in general.

Appendices?

Built-in arithmetic operations

+ addition      * multiplication      / division
- subtraction      ** exponentiation ("raise to a power")      % remainder (modulus)

Strings; string operations

operatordescriptionoperatordescription
' single quotes surround a string in membership
" double quotes surround a string len( ) length
+ concatenation [ : ] slicing
* repetition for ... in ... iteration
[ ] indexing

String methods

Strings are objects, and they have methods (properties) that operate on them. These methods don't change the string, they return a modified copy.

methoddescription
.center(WIDTH) center the string in a WIDTH-space field
.count(ITEM) count how many times the character ITEM occurs in the string
.ljust(WIDTH) left-justify the string in a WIDTH-space field
.rjust(WIDTH) right-justify the string in a WIDTH-space field
.upper() convert all characters to uppercase
.lower() convert all characters to lowercase
.find(ITEM) index of the beginning of ITEM (a substring) within the string
.split(SPLITCHAR)split into tuple of substrings separated by SPLITCHAR