COSC 1336 | PyThon


Using the Command Line Interactive Mode


The command line (a.k.a. command prompt and cmd) has been a common interface on personal computers since the 1980's and remains a useful tool today. System and database administrators and web developers frequently rely on the minimalist, yet powerful, capabilities of the cmd.exe program. In this chapter, we will use the command.exe (command line) to run the Python interpreter.

Running the Python Interpreter

There are two ways that the command line is used to run Python programming statements. With the first method, statements are typed directly at the command line and the interpreter runs the code at the end of each statement. The other technique is to write the code in a Python program file with a .py extension and have the interpreter run that file. We look more closely at the interactive technique below and the file method (script mode) in the next chapter.

Easy to Confuse the Two Modes

Since both the interactive mode and the script mode run from the command window, it is easy for beginners to forget which mode they are running. Remember that in interactive mode, three right angle brackets '>>>' are the prompt. Whereas in script mode, the prompt looks something like: C:\0-yourlastname> (in Windows). At a recent Python Conference a speaker made the same observation.

Using the Interpreter at the Command Line

Start Python with 'python' at the command line. Type the statements as shown below to see the interpreter in action. Each prompt contains a print statement. print() is a system-level function that is used to display content from the interpreter back out to the command window. System-level (a.k.a built-in) functions are included as part of Python to accomplish common programming tasks. In subsequent chapters we will write user-defined functions in which we define the code steps.

Let's begin by looking at a few examples with strings. Strings are found in most (essentially all) popular computing languages. They are the mechanism used to convey human language and are therefore ubiquitous in computing. Just as string theory is considered by some physicists to be a unifying explanation of the universe, strings are the cohesive constructs through which humans communicate with computers. A string is simply a list of characters. In Python, a string can be enclosed in either single or double quotes. The following are examples of strings:

  • "abc"
  • 'xy89z&$#'
  • "123"
  • "Python is a powerful and popular programming language."

In the examples above, perhaps the only one that seems a little strange is "123". Even though the characters one, two, and three are numerical, "123" is a string since it is enclosed in quotes. If we need to use "123" as a number then we must convert it to a numerical type which we will do a little later in this chapter.

See the command window output below. The built-in function print() is used to output content to the console window. Built-in functions are part of the interpreter and are always available for use in code. That is, they can be called at any time. See the following link for a list of all ~70 Python built-in functions. Many of the functions will be covered in this course.

Note the \n characters included in each of the lines below. \n is used to create a 'new line' (a.k.a. carriage return or line feed). In the first statement, there is a \n at the beginning of the line but not at the end. See how the 'Welcome' line has a blank line before it but not after. All other print lines have a \n before and after the string and those output lines have a blank line before and after the output.

When either single or double quotes are desired in the output, the alternative quote type must be used to enclose the print string. For instance, in the second print statement, notice the 'other' in single quotes. Double quotes enclose the print string. Alternatively, in the next print statement, "other" is surrounded by double quotes so single quotes are used to enclose the print statement.

Another point to note is the triple quotes in the last two print statements. When triple quotes are used (either double or single) then both quotes types can be used in the print string. This can be observed in the last two print statements. Triple quotes also correctly capture strings that span multiple lines.

To exit the Python interpreter, type quit() [ENTER] or exit() [ENTER]. Ctrl-z [ENTER] also exits on Windows and Cmd-d exits on Linux or OSX.

The lines below demonstrate that the use of the built-in function print() is not required at the command line to display output. It can be done as shown. Note that print() is required for output in files.

Setting an Environment Variable for the Interpreter (optional)

Before we look at a few more examples using the interpreter at the command line, I want to set an environment variable that makes working with the interpreter a little more convenient. This step, setting a startup script, is optional since we will not devote much time to working in interactive mode. Also, note that administrator access is required to set an environment variable so this step cannot be performed on ACC lab machines.

Open Notepad++ and write the following Python script and save it as C:\Python35\ . This Python script will enable us to clear the interpreter screen by typing cls. If you do not have Notepad++, it is available as a free download from here. Or, if you prefer, you can use the a text editor of your choosing.

Now we need to set an environment variable that will run the script every time we open Python. Open Control Panel | System | Advanced System Settings as shown:

Note: There are a number of basic computer operations used in the course for which explicit instructions are not provided. For instance, in the instruction above, suppose that you do not know how to access the Control Panel. Fortunately, a quick internet search reveals many helpful links on the topic. If you do not already possess accomplished search skills then you should work to improve in that area. This skill is called "Google Fu" and increase your Google Fu you must. Software developers rely heavily on their ability to obtain technical information from internet sources.

In the next window that appears, select Environment Variables:

Under System variables, Select New...:

In the dialog below, enter PYTHONSTARTUP for the name and C:\Python35\ for the value and then select OK | OK | OK and then close the Control Panel window.

More Interpreter Examples

Now that we have a startup script set, it will run each time Python is started. Open a command window, start Python, and enter the sample lines below. (Note: to cycle through previously used commands use the up and down arrow keys. This feature is called command history.) You may have noticed a few new lines like 'i = 2' and 'j = 3'. In these lines, variables are being declared and assigned values. Variables are locations that are used to keep track of values. We learn more about variables and objects in upcoming chapters. On the next line, 'i + j', simple addition is performed and the sum appears after pressing <ENTER>.

Notice the .format(i+j) on the next line. format() is a method of the string object that is used here to include output within a string. The replacement field identified by the {} is a target for the content within the parenthesis of the format(), in this case "i+j". So, we see the line "I could code Python for 5 hours straight!"where calculation of i+j was substituted for {} resulting in 5 replacing the {}.

Another important concept in computer science is the expression which can be defined as "one or more values". The values can be constants, variables, or objects. The values, each an expression, can be combined to form larger expressions. In the output below, the following are all examples of expressions:

  • String literal objects: "Hello." and 'Python is fun.'
  • Variables: i and j
  • Numeric literals: 2 and 3
  • Assignment statements: i = 2, j = 3, and i + j

An expression in computer science is related to an expression in mathematics.

See these Wikipedia articles for more on expressions.

Expression in computer science. and Expression in mathematics.

Pressing <ENTER> after typing 'cls' clears the screen to result in:

In the next example, variables are used again but this time they are used in an if statement that spans multiple lines. When an if statement is followed by a :, the interpreter uses blocks (identified by the three ...) to align the code. Note the indentation levels. To exit the blocks feature, press <ENTER> twice.

Notice that the print("a < b") line is indented two spaces. Most programming languages ignore white space. This means that extra spaces or tabs in C++, C#, Java, JavaScript, or PHP are discarded. However, Python uses indentation to identify blocks of code. It does not matter how many spaces are used for indentation but they must be consistent. We will see this concept repeated frequently throughout the course.

Since a is indeed less than b, the line print("a < b") is executed and we see the output of a < b. If the value of a was not less than b then the else portion of the if statement would have been executed and the line "a is not less than b" would have been printed.

The next few lines show the use of string continuation. The backslash is used on two lines to allow the string to span multiple lines. Note that the string is printed on a continuous line when output.

To demonstrate the importance of indentation, in the next section of code the print("a < b") statement is not indented properly which results in an IndentationError as shown.

Remember to code the examples and ensure you see the same output as that displayed.