Python Files,Test Code and Scripts
Python Files: Files, which are also known as modules, are where we can store our code. This is really helpful for more serious programming, because we don’t want to start over on a lengthy function definition only to fix one error. In essence, by doing this, we are creating our own modules, much like the ones found in the Python library. For instance, we can use any text editor3 to enter the code into a file and put our squaring function example there. The code is shown in detail below.
Phyton Files
def square (x): return x*x
Notice that we omit the prompt symbols >>>, … when typing the code into a file, but the indentation is still important. Let’s save this file under the name “SquaringFunction.py” and then open a terminal in order to run it:
doty@brauer:~% python Python 2.5.2 ( r252 :60911 , Apr 21 2008 , 11:12:42) [GCC 4.2.3 ( Ubuntu 4.2.3 -2ubuntu7)] on linux2 Type " help", " copyright", " credits" or " license" for more information. >>> from SquaringFunction import square >>> square (1.5) 2.25
Take note of the fact that I could not utilize the function until I imported it from the file. Just like with library modules, importing a command from a file has the same effect. Due to this resemblance, some individuals even refer to Python files as “modules.” Also take note of the import command’s omission of the file’s extension (.py).
Phyton Testing code
As indicated above, code is usually developed in a file using an editor. To test the code, import it into a Python session and try to run it. Usually there is an errors, so you return to the file, fix it, and run the test once more. You must keep doing this until you are confident that the code is functional.
The development cycle is the name given to the entire procedure.
There are two different kinds of errors that you will run into. Errors in syntax happen when a command’s form is incorrect. This might occur when you type carelessly and misspell words or call something by the wrong name, among other things. A syntax error in Python will always result in an error message.
Phyton Scripts
Python instructions can be run as scripts if you use Mac OS X or another Unix-based operating system (like Linux). Here is one instance. Create a file called SayHi with the following lines in it using an editor.
#! /usr/bin/ python print " Hello World!" print "- From your friendly Python program"
Python is informed that this is a script in the first line. Make the file executable by entering chmod 755 SayHi in the terminal after saving it. In the terminal, type./SayHi to launch the script. You can launch the script by entering SayHi if you relocate it somewhere along your search path.
As far as I know, it is impossible to run Python scripts in a similar way on a Windows machine.