Things you don't need to know about python
There are several Python features that you might have copied from one example to the next without knowing quite what they're for. This document strives to fill in some of these gaps in understanding.
Versions
Sooner or later you'll come up against problems caused by Python existing in several versions. The main split is between Python 2 and Python 3, but there are also differences between distributions (e.g. which packages and editors are provided). There are also differences in behaviours depending on the operating system used (file-opening for example may differ between Windows and MacOS). So when you report a problem it's worth including information about which Python you're using, and on what tye of machine. The following code gives some system information that may help
import sys sys.executable sys.version_info sys.path sys.platform
If you're searching for information about (say) the len
command in Python 3, it's worth searching for python 3 len
rather than python len
.
main
The scripts we produce often end with something like
if __name__ == '__main__': ...
Python scripts can be imported so that the functions in them can be used by other scripts. Python scripts can also be run directly from the command line. Ideally almost every importable Python module can do something useful if called from the command line. The special line makes this possible. if __name__ == '__main__'
is only true if the file is called rather than imported, so if you wanted function fun1
to be called when the file's executed but not when the file's imported, use
def fun1(): print("hello"); if __name__ == '__main__': fun1()
Paths
When you run or import a python file, which of the many files with that name in the system will be used?
You can find out where python looks for imported files by running
import sys print(sys.path)
Python will look in these folders in order, looking for a file with the requested name.
In Unix a variable called PYTHONPATH
(a list of folders separated by colons) shows extra folders where python will look for imported files. This variable belongs to the shell (the command-line interpreter). If you keep all your python modules in a folder call pythonstuff
in your home folder, you can make the modules importable from anywhere using
export PYTHONPATH=${PYTHONPATH}:~/pythonstuff
at the start of your session. This will affect everything subsequently done from the window you type the command in. It won't affect what happens in a completely separate window.
Misc
- range - In Python 2 this returned a list. In Python 3 it returns an iterator. Except for speed, this makes no difference when writing
for
loops, but if you really do want a list, you can use (say)list(range(5))
.