I l@ve RuBoard Previous Section Next Section

1.6 Exercises

Okay: time to start doing a little coding on your own. This session is fairly simple, but a few of these questions hint at topics to come in later chapters. Remember, check Appendix C, for the answers; they sometimes contain supplemental information not discussed in the chapters. In other words, you should peek, even if you can manage to get all the answers on your own.

  1. Interaction. Start the Python command line, and type the expression: "Hello World!" (including the quotes). The string should be echoed back to you. The purpose of this exercise is to get your environment configured to run Python. You may need to add the path to the python executable to your PATH environment variable. Set it in your .cshrc or .kshrc file to make Python permanently available on Unix systems; use a setup.bat or autoexec.bat file on Windows.

  2. Programs. With the text editor of your choice, write a simple module file梐 file containing the single statement: print 'Hello module world!'. Store this statement in a file named module1.py. Now, run this file by passing it to the Python interpreter program on the system shell's command line.

  3. Modules. Next, start the Python command line and import the module you wrote in the prior exercise. Does your PYTHONPATH setting include the directory where the file is stored? Try moving the file to a different directory and importing it again; what happens? (Hint: is there still a file named module1.pyc in the original directory?)

  4. Scripts. If your platform supports it, add the #! line to the top of your module1.py module, give the file executable privileges, and run it directly as an executable. What does the first line need to contain?

  5. Errors. Experiment with typing mathematical expressions and assignments at the Python command line. First type the expression: 1 / 0; what happens? Next, type a variable name you haven't assigned a value to yet; what happens this time? You may not know it yet, but you're doing exception processing, a topic we'll explore in depth in Chapter 7. We'll also see Python's source debugger, pdb, in Chapter 8; if you can't wait that long, either flip to that chapter, or see other Python documentation sources. Python's default error messages will probably be as much error handling as you need when first starting out.

  6. Breaks. At the Python command line, type:

    L = [1, 2]

    What happens? If you're using a Python version older than 1.5.1, a Ctrl-C key combination will probably help on most platforms. Why do you think this occurs? What does Python report when you type the Ctrl-C key combination? Warning: if you have a Python older than release 1.5.1, make sure your machine can stop a program with a break-key combination of some sort before running this test, or you may be waiting a long time.

I l@ve RuBoard Previous Section Next Section