Writing and executing Python program
·
Python code can
be written using any plain text editor that can load and save text using
either the ASCII or the UTF-8 Unicode encoding.
·
By default,
Python files are assumed to use the UTF-8-character encoding, a superset of
ASCII that can represent pretty well every character in every language.
·
Python files
normally have an extension of .py, although on some Unix-like systems
(e.g., Linux and Mac OS X) some Python applications have no extension, and
Python GUI (Graphical User Interface) programs usually have an extension of.
pyw, particularly on Windows and Mac OSX. In this book we always use an
extension of .py for Python console programs and Python modules, and. pyw for
GUI programs.
·
Just to make sure
that everything is set up correctly, and to show the classical first example,
create a file called hello.py in a plain text editor (Windows Notepad is
fine—we’ll use a better editor shortly), with the following contents:
#!/usr/bin/env python3
print("Hello", "World!")
·
The first line is
a comment. In Python, comments begin with a # and continue to the end of the
line. (We will explain the rather cryptic comment in a moment.)
·
The second line
is blank—outside quoted strings, Python ignores blank lines, but they are often
useful to humans to break up large blocks of code to make them easier to read.
·
The third line is
Python code. Here, the print() function is called with two arguments, each of
type str (string; i.e., a sequence of characters).
·
Each statement
encountered in a .py file is executed in turn, starting with the first one and
progressing line by line. This is different from some other languages, for
example, C++ and Java, which have a particular function or method with a
special name where they start from.
·
The flow of
control can of course be diverted as we will see when we discuss Python’s
control structures in the next section.
Now that we have a program, we can run it.
·
Python programs
are executed by the Python interpreter, and normally this is done inside a
console window. On Windows the console is called “Console”, or “DOS Prompt”, or
“MS-DOS Prompt”.
·
Start up a
console, and on Windows enter the following commands (which assume that Python
is installed in the default location)—the console’s output is shown in
lightface; what you type is shown in bold:
C:\>cd c:\py3eg
C:\py3eg\>c:\python31\python.exe
hello.py
·
Since the cd
(change directory) command has an absolute path, it doesn’t matter which
directory you start out from. Unix users enter this instead (assuming that
Python 3 is in the PATH):
$ cd $HOME/py3eg
$ python3 hello.py
In both cases the output should be the same:
Hello World!