Python in a Command Window

A computer program is a collection of instructions that a computer runs to perform a task. In our case, the instructions will be written in the Python language. As this course progresses, we will learn how to create a website that uses HTML and JavaScript as the front-end (client) and then Python and Django on the back-end (server). For now, let us see how we can work with Python using the command line in Microsoft Windows (on a Mac it is called the Terminal window). The command line in Windows is an environment where the user types commands rather than clicking with the mouse. In “old school” terms, it is a shell system that uses text from the keyboard to provide instructions to the operating system. An advantage of the shell window (or command window) is that the interface can be faster, depending on how fast you type, but the disadvantage is that you must learn a whole new set of commands to type.

To open the command window, click on the Windows 10 Start button and type cmd and press the Enter key. A window like the one below will be displayed.

You now have access to the Python programming environment! Simply type Python and press the Enter key. In the Mac environment, you will open a Terminal window. There are two ways you can do this. One is by clicking the Launchpad icon in the Dock and typing Terminal in the search field and then clicking on Terminal. The other is to use the Finder to open the /Applications/Utilities folder and then double-click on Terminal.

This begins the Python environment. Notice that this version is running Python 3.10.6. The >>> is the command prompt indicating that it is waiting for you to type Python statements.

To exit the Python shell window, type exit() and press Enter. Another way to exit is to press Ctrl+Z and press Enter. Control will be passed back to the command window. To leave the command window, type exit and press Enter.

Watch the following video to see how you can use Python in Microsoft’s command window.

NOTE: This video uses an older version of Python 3.8.3 but the functionality and appearance are the same as the current version you just installed.

If you had a file that contained Python source code, you could execute that file at the command line. For example, if the file name were MyScript.py, you could execute the file by typing the following at the command line prompt:

python MyScript.py

Then press Enter. That would execute the source code contained in the MyScript.py file.

NOTE: The .py extension indicates the file’s contents contain Python source code—much like .jpg, .css, or .html indicate the contents of a specific file.

What does this mean to you? Do you really think you are going to type all your Python source code in the command window? That would defeat the purpose of having a visual programming IDE.