Functions Top Input and Output Contents

Python Programs and Using Files

After a while, it gets rather tedious to cut and paste into the Python interpreter. A more efficient method is to store your program in a text file and then load the file.

I use vim as my text editor. Vim is an editor that was written by programmers for programmers (emacs is another such editor) and serious Computer Scientists and Programmers should learn vim (or emacs).

Your first program

Create a text file named hello.py. The name really doesn't matter and doesn't have to end in .py (the .py is a convention to remind us this file contains Python source code). Place in the file:

print("hello, world!");

Save your work and exit the text editor.

Now execute the following command at the system prompt (not the Python interpreter prompt!):

    python3 hello.py

You should see the phrase:

    hello, world!

displayed on your console. Here's a trace using Linux:

    lusth@warka:~$ python3 hello.py
    hello, world!
    lusth@warka:~$

The lusth@warka: $ is my system prompt.

Vim and Python

Move into your home directory and list the files found there with this command:

    ls -al

If you see the file .exrc, then all is well and good. If you do not, then run the following command to retrieve it:

    (cd ; wget troll.cs.ua.edu/cs150/.exrc)

This configures vim to understand Python syntax and to color various primitives and keywords in a pleasing manner.

A Neat Macro

One of the more useful things you can do is set up a vim macro. Edit the file .exrc in your home directory and find these lines:

    map @ :!python %^M
    map # :!python % 
    set ai sm sw=4

If you were unable to download the file in the previous section, just enter the lines above in the .exrc file.

The first line makes the '@' key, when pressed, run the Python interpreter on the file you are currently editing (save your work first before tapping the @ key). The ^M part of the macro is not a two character sequence (^ followed by M), but a single character made by typing <Ctrl>-v followed by <Ctrl>-m. It's just when you type <Ctrl>-v <Ctrl>-m, it will display as ^M. The second line defines a similar macro that pauses to let you enter command-line arguments to your Python program. The third line sets some useful parameters: autoindent and showmatch. The expression sw=4 sets the indentation to four spaces.

Writing Python Programs

A typical Python program is composed of two sections. The first section is composed of variable and function definitions. The next section is composed of statements, which are Python expression. Usually the latter section is reduced to a single function call (we'll see an example in a bit).

The hello.py file above was a program with no definitions and a single statement. A Python program composed only of definitions will usually run with no output to the screen. Such programs are usually written for the express purpose of being included into other programs.

Typically, one of the function definitions is a function named main (by convention); this function takes no arguments. The last line of the program (by convention) is a call to main. Here is a rewrite of hello.py using that convention.

def main():
    println("hello, world!")
    return 0

main()

This version's output is exactly the same as the previous version. We also can see that main implements the function pattern since it has a non-None return value. Generally, a zero return value for main means that no errors were encountered. Typically, non-zero return values for main are used to indicate errors, with each value associated with a specific error.

Order of definitions

A function (or variable) must be created or defined18 before it is used. This program will generate an error:

main()           #undefined variable error

def main():
    y = 3
    x = y * y
    print("x is",x)
    return 0

since main can't be called until it is defined. This program is legal, however:

def main():
    x = f(3)
    print("x is",x)
    return 0

def f(z):
    return z * z

main()

because even though the body of main refers to function f before function f is defined, function f is defined by the time function main is called (the last statement of the program).

Here is the order of steps taken when this program is run:

  1. the function main is defined
  2. the function f is defined
  3. the function main is called
    1. the statement x = f(3) is evaluated
    2. the function f is called
      1. the formal parameter z is set to 3
      2. the square of z is computed
      3. the function f returns the value 9
    3. x is assigned the value 9
    4. the statement print("x is",x) is evaluated
    5. the text "x is 9" is printed
    6. the function main returns zero
  4. the program ends

At this point, you should type this program into a file and then run it. If you do so, you should see the following output, as expected:

    x is 9

A useful trick to understanding the flow of a program is to place print statements throughout the code and try to guess, before running the program, the order in which those added statements display text to the console.

Importing code

One can include one file of Python code into another. The included file is known as a module. The import statement is used to include a module:

from moduleX.py import *

where moduleX.py is the name of the file containing the Python definitions you wish to include. Usually import statements are placed at the top of the file. Including a module imports all the code in that module, as if you had written it in the file yourself.

If moduleX.py has import statements, those modules will be included in the file as well.

Import statements often are used to include the standard Python libraries.

lusth@cs.ua.edu


Functions Top Input and Output Contents