Python commands can be used interactively, as we have just seen, but they can also be stored in a file, called a Python Module, provided that it ends with an extension of .py, and follows some basic formatting requirements, like the use of indentation to identify what statements belong in a block. More on this later.
Any Python statements you can execute interactively can be put into a Python module and then executed at the command line or loaded into IDLE or another program that can ediot and execute Python modules (Scite is a good example). Say you have created the classic first program "Hello World" in a Python module, called hello.py. It would contain one line: print "Hello World", and would be executed by typing at the command shell prompt (not the Python prompt):
Python contains many built-in methods, and we will explore some of them as needed. One of the most common and useful ones is the range method. It generates a list, with N entries in it, sequentially numbered, starting from 0. N is passed to the method as an argument, in parentheses, like this:
This is useful in programs in which you need to iterate over a list, or perform some function N times. Here is the first example in which formatting in Python is needed. We have to indent the line print i underneath the line for in in range(10): in order to make clear to the Python interpreter which lines of the script are to be repeated 10 times. If we put this into a loop.py module and want to print the word "Done!" at the end of the list, the script would look like this:
If we have saved this as loop.py, then we can run it at the command prompt by typing python loop.py, and would see the following output:
Now that we have used a built-in Python function, try writing one of your own. For example, you could compute the square of a number with a function like this:
It would not be necessary to implement this particular method, however, since it is built into Python's Math package. To use functions in the Math package, you have to import the functions or the whole package. Here are some options:
Note the difference in usage depending on which way you choose to import a function. The last one, using a * to import all the functions, is acceptable for an interactive session, but is a poor choice in a complex program you write, because each imported function has a name that gets stored in a Python Namespace used to keep track of all the functions, and this can get cluttered or confusing if you happen to import from multiple packages and don't realize that the same function name is used to do different things in two different packages. You will see imports of many packages in the OPUS system. One of the main ones is covered in the next section: Numpy.