Instant Gratification : The Simplest Possible Conversation

There are two ways to exercise the Python program: interactively and with a script. In interactive mode, Python responds to each statement that we type in. In script mode, we give the Python program a file with a script of statements and turn it loose to interpret all of the statements in that script. Both modes produce identical results. Our goal is to write finished programs that will be run as a script. It’s a long journey to scripting, which begins with some first small steps. We have to start with experimenting and exploring, so we’ll use Python interactively. This gives us the instant gratification of a dialog with the Python program.

To be sure that we’ve got the basics installed and working, we’ll use Python directly for our interactions. In the next chapter, we’ll add the IDLE tool to the mix.

We’ll look at starting Python in several sections: The Windows Command Prompt, The Mac OS Terminal Tool, and The GNU/Linux Terminal Tool. We’ll look at ending out conversation in How Do We Stop?.

The real work starts in Your First Conversation in Python: miles per gallon. We’ll look at numbers in Decimal-Points and Accuracy and look at more arithmetic in More Conversations on Arithmetic.

We’ll examine some core features of the language in Parenthesis and Precedence, Long-Winded Statements, and More About Punctuation. We’ll answer a few questions in Direct Python Interaction FAQ.

The Command or Terminal tool use of Python is the simplest and most ubiquitous way to use Python. This doesn’t have flashy, interactive, colorful screens; it’s just plain text. When we get to Fit and Finish: Complete Programs, we’ll see that this way of using Python has an elegant simplicity that the experts use heavily.

The Windows Command Prompt

The command prompt is sometimes hard to find in Windows. In Windows 2000, you have to look in the Start menu under Programs, and then under Accessories to find the Command Prompt.

You can also use the Run... menu item in the Start menu. This will give you a small dialog box where you can type the name of a program. The name of the command prompt is just cmd. You can type cmd, and click Okay.

When you run the command tool, it will present a black window with a prompt from the operating system that looks something like C:\Documents and Settings\SLott>. Here, you can type the word python, hit return, and you’re off and running.

Tip

Debugging Windows Command Prompt

In the unlikely event that you can’t use Python from the Command Prompt, you have an issue with your Windows “path”. Your path tells the Command Prompt where to find the various commands. The word python becomes a command when the python.exe file is on the system’s path.

Generally, you should reinstall Python to give the Python installer a chance to set the path correctly for you. If, for some reason, that doesn’t work, here’s how you can set the system path in Windows.

Setting the Windows Path

  1. Open the Control Panel.

    Use the Start menu, Settings sub menu to locate your Control Panel.

  2. Open the System Control Panel

    Double-click the System Control Panel. This opens the System Properties panel.

  3. Open the Advanced Tab of the System Control Panel

    Click the Advanced tab on the System Control Panel.

    There are three areas: Performance, Environment Variables and Startup and Recovery. We’ll be setting the environment variables.

  4. Open the Environment Variables of the Advanced Tab of the System Control Panel

    Click the Environment Variables... button.

    This dialog box has a title of Environment Variables. It shows two areas: user variables and System variables. We’ll be updating one of the system variables.

  5. Edit the Path variable

    This dialog box has a title of Environment Variables. Scroll through the list of System variables, looking for Path. Click on the Path to highlight it.

    Click the Edit... button.

    This dialog box has a title of Edit System Variable. It has two sections to show the variable name of Path and the variable value.

  6. Add Python’s location to the Path value

    This dialog box has a title of Edit System Variable. It has two sections to show the variable name of Path and the variable value.

    Click on the value and use the right arrow key to scroll through the value you find. At the end, add the following ;C:\python25. Don’t forget the ; to separate this search location from other search locations on the path.

    Click OK to save this change. It is now a permanent part of your Windows setup on this computer. You’ll never have to change this again.

  7. Finish Changing Your System Properties

    The current dialog box has a title of Environment Variables. Click OK to save your changes.

    The current dialog box has a title of System Properties. Click OK to save your changes.

The Mac OS Terminal Tool

In the Applications folder, you’ll find a Utilities folder. In the Utilities folder, you’ll find a program named Terminal. Double click Terminal and you’ll get a window with a prompt from the operating system that looks something like [DVDi-Mac-1:~] slott%. Here, you can type env python, and you’re off and running.

You might want to drag the Terminal icon onto your dock to make it easier to find.

The GNU/Linux Terminal Tool

The Fedora Linux desktop, for example, has a Start Here icon which displays the applications that are configured into you GNOME environment. The System Tools icon includes the Terminal application. Double click Terminal and you’ll get a window which prompts you by showing something like [slott@linux01 slott]$. In response to this prompt, you can type env python, and you’re off and running.

For non-Gnome Linux and Unix variants, you must find your Terminal tool, into which can type python.

How Do We Stop?

Once the Python program has started, it looks something like the following. It doesn’t matter whether Python starts up from the command prompt or terminal window, the basic operation is the same. The window title and background color may be different, but our interaction with Python will be the same.

MacBook-5:PythonBook-2.5 slott$ python
Python 2.5.4 (r254:67917, Dec 23 2008, 14:57:27)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

When we get the >>> prompt, the Python interpreter is listening to us. We can type any Python statements we want. Each complete statement is executed when it is entered.

To finish using Python, we enter the end-of-file character. We do this when we’re completely done with all of our work. We don’t absolutely have to do this, because we can always just exit the Command Prompt or Terminal. When we stop the Terminal, the running Python program will be killed, also.

MacOS and GNU/Linux. The polite way to tell Python that we’re done is Ctrl-D.

Windows. The polite way to finish a conversation with Python is Ctrl-Z, followed by Enter.

Your First Conversation in Python: miles per gallon

The Python program’s job is very simple: it prompts you for a statement, executes the statement you entered, and then responds back to you with the result of executing the statement. This little three-step loop is all that Python does. Of course, as we will see, the real power comes from the wide variety of statements we provide in the Python language.

Important

Don’t Forget to Run Python

While this may seem like a silly reminder, it’s important to start the Python program. We emphasize it because it isn’t always obvious what piece of software processes our Python language statements.

In The Python Program and What It Does we described our four-tiered device built from the Computer System, Operating System, Terminal (or Command Prompt) and Python. First, we start the computer system with the power button. The Operating System starts more-or-less automatically. Second, we have to locate the Terminal (or Command Prompt), called a “shell”. Third, we run Python.

Each tier of software has it’s own unique prompt. The basic operating system presents a slick GUI desktop metaphor with colorful icons and menus. The shell provides a technical-looking prompt like C:\Documents and Settings\SLott>, or [DVD-iMac-2:~] slott%. Python provides the >>> prompt that tells us we can enter a Python statement.

Bottom Line. We’re always interacting with some program on our computer. We can’t “simply type things”; we have to run a program which will respond appropriately when we give that program statements in a language it can process. If you don’t see the >>> prompt, you’re not interacting with Python.

Since we are all newbies to programming, we’ll start with some very simple Python interactions, just to see what kinds of things Python can do. We’ll start the Python program and then type Python statements that evaluate a simple formula. For these first few examples, we’ll include the reminder to start running Python.

This first example will show the mathematical operation of ÷. If you look at your computer keyboard, you won’t find the ÷ key. Python uses / (and //) for division.

MacBook-5:~ slott$ python
Python 2.5.4 (r254:67917, Dec 23 2008, 14:57:27)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 351/18
19
  1. The shell prompted me with MacBook-5:~ slott$. I typed python to start the python program running.
  2. Python provided some information on itself.
  3. Python prompted me with >>>. I typed 351 / 18 to compute miles per gallon I got driving to Newark and back home. This is a complete Python statement, and Python will evaluate that statement.
  4. Python responded with 19: a rotten 19 miles per gallon. I’ve got to get a new car that uses less gasoline.

This shows Python doing simple integer arithmetic. There were no fractions or decimal places involved. When I entered 355 / 18 and then hit Return, the Python interpreter evaluated this statement. Since the statement was an expression, Python printed the results.

The usual assumption for numbers is that they are integers, sometimes called whole numbers.

Note that Python does not like , in numbers. Outside Python, we write large numbers with , to break the numbers up for easy reading. (The exception is the calendar year, where we omit the ,: we write 2007, not 2,007.) Python can’t cope with , in the middle of numbers. The mileage on my odometer reads 19,241. But, in Python we write this as 19241.

Bottom Line. For now, be comfortable that Python is perfectly happy with whole numbers. Remember to avoid commas. We sometimes call these numbers ints, short for integers. Later, we’ll see that Python has a pretty expansive set of numbers available to work with.

Decimal-Points and Accuracy

That calculation was nice, but you’ll notice that whole numbers aren’t really very accurate. If you pull out a calculator, you’ll see that Python got a different answer than your calculator shows.

If you include a period in your numbers, you get “floating decimal point” numbers. We call these floating-point or floats. The number of digits on either side of the decimal point can “float”. Floating point numbers are handy for many kinds of calculations.

Our previous conversation used whole numbers. Let’s try again, using floating-point numbers.

>>> 351. / 18.
19.5
  1. I typed 351. / 18. to compute miles per gallon I got driving to Newark and back home.
  2. Python responded with 19.5: the more accurate 19.5 miles per gallon.

Floating-point isn’t adequate for everything, so there’s another kind of number that we’ll get to later. When we do financial calculations on US dollars, the decimal point is fixed; we have two digits to the right of the decimal point and no more. These fixed-decimal point numbers aren’t a built-in feature of Python, but there are ways to extend Python with a library that gives us this capability.

Bottom Line. For now, be comfortable that Python is perfectly happy with floating-point numbers that have about 17 total digits of accuracy, but a range that is huge. Remember to include a decimal point to tell Python that you want to see decimal places in the calculation. Also, remember to avoid commas, they’re just confusing.

More Conversations on Arithmetic

So far, we’ve given arithmetic expressions to Python and Python’s response is to evaluate those expressions. When we look at our keyboard, we can see that we have / (for division), + for addition and - for subtraction. What about multiplication (\times)? Square roots (\surd)? Raising to a power? These aren’t keys on a standard keyboard.

Here are the arithmetic operations that Python recognizes in forms very similar to the way mathematics is written:

  • Addition (+) is the + character. You say 123+456 to add two numbers.
  • Subtraction (-) is the - character. You say 9116-8765 to find the difference between two numbers.
  • Multiplication (×) is the * character. You say 19*18 to find the product of two numbers.
  • Division (÷) is the / character and the // sequence of characters. You say 351/18 to find the quotient of two numbers.
  • Raising to a power (a^p) is the ** sequence of characters. You can say 5**2 to raise 5 to the 2nd power, 5^2.

Additionally, Python (and many other programming languages) provide two handy operators that mathematicians don’t normally write down in this form. Mathematicians may talk about “modular” arithmetic, with something like a \bmod m. This is written in Python using the % character. For non-mathematicians, this is the remainder after division.

>>> 355 % 113
16
>>> 355 / 113
3

Here’s what this shows us: 113 goes into 355 with 16 left over. Mathematically, 355 = 3 \times 113 + 16.

We’ll look at all of these operators closely in Simple Arithmetic : Numbers and Operators.

Parenthesis and Precedence

The usual mathematical rules of operator precedence apply to Python expressions: multiplies and divides will be done before adds and subtracts. Plus, we get to use () are used to group terms against precedence rules. Unlike mathematics, we can’t use [] and {} in arithmetic expressions. Mathematicians can use these, but in Python, we have to limit ourselves to just ().

For example, converting 65 ° Fahrenheit to Celsius is done as follows.

>>> (65 - 32) * 5 / 9
18
>>> ((65 - 32) * (5 / 9))
0
>>> ((65 - 32) * (5 / 9.))
18.333333333333336

We have to put the 65-32 in parenthesis so that it is done before the multiply and divide. Also, you’ll note that when one number is floating point (9.) it forces the calculation to be done as floating-point.

What would happen if we said 65-32*5/9? Try it first, to see what happens.

If we don’t include the () for grouping, then Python would do what every mathematician would do: compute 32*5/9 first and then the difference between that and 65. Python did what we said, but not what we meant. We know the answer is wrong because 65 ° Fahrenheit can’t be the impossibly hot 48 ° Celsius.

In the second example, we put in extra () that don’t change the resulting answer.

Long-Winded Statements

Python prompts us with the basic “I’m listening” prompt of >>> When we type an expression statement, Python prints the result for us, and then another prompt.

Python has a second prompt that you will see from time to time. It indicates that your statement isn’t complete, and more is required. It’s the “I’m still listening” prompt of .... Here’s how it works.

For this section only, we’ll emphasize the usually invisible Return key by showing it as ↵. When we start using compound statements in Processing Only When Necessary : The if Statement, we’ll add some additional syntax rules. For now, however, we have to emphasize that statements can’t be indented; they must begin without any leading spaces or tabs. Here’s a simple case: converting 65 ° Fahrenheit to Celsius.

>>> (65 - 32) * 5 / 9 ↵
18
>>>

What happens when the expression is obviously incomplete?

>>> ( 65 - 32 ) * 5 / ↵
File “<stdin>”, line 1
  (65-32)*5 /
   ^
  SyntaxError: invalid syntax
>>>

This leads us to the first of many syntax rules. We’ll present them in order of relevance to what we’re doing. That means that we’re going to skip over some syntax rules that don’t apply to our situation.

Important

Syntax Rule One

Statements must be complete on a single line. If the statement is incomplete, you’ll get a SyntaxError response.

Just to be complete, we’ll present syntax rule two, but it doesn’t really have much impact on what we’re going to be doing.

Important

Syntax Rule Two

The invisible end-of-line character is slightly different on different platforms. On Windows it is actually two non-printing characters, where on GNU/Linux and MacOS it is a single non-printing character. You may notice this when moving files back and forth between operating systems.

There is an escape clause that applies to rule one (“one statement one line.”) When the parenthesis are incomplete, Python will allow the statement to run on to multiple lines.

>>> ( 65 - 32 ↵
... ) * 5 / 9 ↵
18
>>>

Yes, we skipped rules three, four and five.

Important

Syntax Rule Six

Python needs to see matching () pairs before it will consider the statement complete.

It is also possible to continue a long statement using a \ just before hitting Return at the end of the line.

>>> 5 + 6 * \ ↵
... 7 ↵
47
>>>

This is called an escape and it allows you to break up an extremely long statement. It creates an escape from the usual meaning of the standard meaning of the end-of-line character; the end-of-line is demoted to just another whitespace character, and loses it’s meaning of “end-of-statement, commence execution now”.

Important

Syntax Rule Five

You can use \ to escape the usual meaning of a character.

Using \ at the end of a line escapes the meaning of the enter key, and allows a statement go continue onto multiple lines. While legal, this isn’t the best policy, and we’re going to avoid doing this.

More About Punctuation

We’ve been ignoring spaces in our expressions. There are some spaces in the examples, but we haven’t been dwelling on precisely how many spaces and where the spaces are allowed. It turns out that spaces other than indentation are very flexible. Indentation is not flexible.

Important

Syntax Rule Nine

You can use spaces and tabs freely to separate tokens, or language elements.

We have found some kinds of mistakes that we can make with unclosed ()‘s and an extra \ at the end of the line. This leads us to an important debugging tip.

Tip

Debugging Typing a Python Statement

When you see the ... prompt from Python, it means that your statement is incomplete. Are you missing a ) to make the () pairings complete? Did you accidentally use the \? Hit Return twice and you’ll get a nice syntax error and you’ll be back at the >>> where you can try again.

Also, you’ll get unexpected errors if you try to use [], and {} the way mathematicians do. Python only uses () to group expressions. If you try to use [], you’ll get a TypeError: unsupported operand type(s) for [] : 'list' and 'int'. If you try to use {}, you get a SyntaxError: invalid syntax.

Getting Help

Python has a help mode and a help() function.

When you enter help(), you’ll wind up in help mode. This has a different prompt, to make it perfectly clear what kinds of things Python is doing.

>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help()

Welcome to Python 2.5!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help>

You can see that the prompt is now help>. To go back to ordinary Python programming mode, enter quit.

help> quit

You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
>>>

You can see that the prompt is now >>>.

If you ask for help on a specific topic, you’ll enter something like this:

>>> help("EXPRESSIONS")

You’ll get a page of output, ending with a special prompt from the program that’s helping to display the help messages. The prompt varies: Mac OS and GNU/Linux will show one prompt, Windows will show another.

Mac OS and GNU/Linux. In standard OS’s, you’re interacting with a program named less; it will prompt you with : for all but the last page of your document. For the last page it will prompt you with (END).

This program is very sophisticated. The four most important commands you need to know are the following.

q Quit the less help viewer.

h Get help on all the commands which are available.

⎵ Enter a space to see the next page.

b Go back one page.

Windows. In Windows, you’re interacting with a program named more; it will prompt you with -- More --. The four important commands you’ll need to know are the following.

q Quit the more help viewer.

h Get help on all the commands which are available.

⎵ Enter a space to see the next page.

Conversational Python Exercises

  1. Simple Commands. Enter the following one-line commands to Python:
    • copyright
    • license
    • credits
    • help
  2. Simple Expressions. Enter one-line commands to Python to compute the following:
    • 12345 + 23456
    • 98765 - 12345
    • 128 * 256
    • 22 / 7
    • 355 / 113

Direct Python Interaction FAQ

Why are numbers 32 bits?

The coffee-shop answer is “that’s the way computers are built”.

The real answer is that the use of 32 bits has a long engineering history. One very important consideration is parallelism. The processor chip designers want to have many things happen at the same time. In the case of retrieving data from memory, getting data in 4-byte chunks will take 1/4 the time of getting data in 1-byte chunks. Modern processors often fetch a very large number of bits from memory and keep it in a special cache buffer on the processor chip.

The number of bits used to represent data has varied somewhat. A comfortable group of bits is called a byte. Some older computers used 9-bits in each byte, and put four of these together to make 36-bit numbers. Early modems used a signal protocol optimized to send 7-bits in each byte.

The 7-bit byte allows for 128 values in a single byte. If we take the US Latin alphabet (26 lower case letters, 26 upper case letters, 10 digits, 40-odd punctuation marks) have about 96 characters. Adding some additional codes for housekeeping, we have 128 character codes, which only needs a 7-bit number to encode each character.

We can then use an eighth bit to carry a primitive error-detection code. We can insist that each valid character code have an even number of bits switched on. If we receive a character with an odd number of bits, we know that a bit got garbled. This is one of the many historical precedents that made 8-bit bytes appealing.

Also, of course, there is an elegant symmetry to using 8-bit bytes when we are using binary number coding. The powers of two that we use for binary number positions are 1, 2, 4, 8, 16, 32, 64 and 128. This sequence of numbers has almost mystic significance. Of course we would prefer 8-bit bytes over 9-bit bytes. 32-bit numbers fit this sequence of numbers better than 36-bit numbers.

From Bytes to Words. Once we’ve settled on 8-bit bytes, the next question is how many bytes make up a respectable “word”. Early computers had 64 kilobytes of memory, a number that requires only 16 bits (2 bytes) to represent. We can use a two-byte register to identify any of the bytes in memory. Many early microprocessors made use of this. The legendary Apple ][ PC had a 6502 processor chip that worked this way. Growing this to 640K only adds 4 more bits to the address information, a kind of half-byte compromise that Microsoft made use of to create DOS for the Intel 8088 processor chip.

In the metric measurement system, a kilometer is 1,000 meters. In the world of computers, there is an elegant power-of-two number that we use instead: 1024. A kilobyte, then is 1024 bytes; a megabyte is 1024*1024 = 1,048,576 bytes; a gigabyte is 1,073,741,824 bytes.

As the amount of memory grew, the size of numbers had to grow so that each location in memory could have a unique numeric address. Currently, 32-bit numbers are oriented around computers with 2 gigabytes of memory. Newer, larger computers use 64-bit numbers so that they can comfortably handle more than 2 Gb of memory.

Is the 8-bit byte still relevant?

When we look at the world’s alphabets, we discover that our 26-letter US Latin alphabet isn’t really very useful. For most European languages that use the Latin alphabet we’ll need to add a number of accented characters. For mathematics, we’ll need to add a huge number of special characters. Once we open the door, we might as well provide for non-Latin alphabets like Greek, Arabic, Cyrillic, Hebrew and others. We’re going to need a lot more than 128 character codes. And then there’s the Chinese problem: there are thousands of individual characters. This is solved by having Multi-byte Character Sets (MBCS). Currently the Unicode standard uses as many as four bytes to represent the world’s alphabets.

Since a byte is no longer an individual character, it is not relevant for that purpose. However, it is the unit in which memory and data are measured, and will be for the foreseeable future.

What Are The Missing Syntax Rules?

Yes, we did skip over rules three, four, seven and eight. These are more advanced topics.

We’ll look at rules three and four in Turning Python Loose with More Sophisticated Scripts. These rules have to do with lines Python ignores, called “comments” and character encoding for Python files.

We’ll look at rules seven and eight in Processing Only When Necessary : The if Statement. These rules have to do with indenting and completing compound statements.