PROJECT 4
Project 3 was kind of brutal, huh? This project is quick and painless. You read about the IDLE Python development environment, which lets you save your code into a file. (No more retyping or cutting and pasting!)
IDLE uses different colors to show the syntax of the Python code you’re writing. It also has tools for commenting and indenting regions in and out. What’s commenting? You read about that, too, along with some editing features that make coding easier.
An integrated development environment is a kind of word processor for coding.
Python comes with a code editor called IDLE. The editor has two main parts:
In Project 1 you pin IDLE (Python GUI) to the top of your Start menu. It should still be up there.
Start IDLE by clicking the Windows Start menu.
When you start IDLE, you should see the Shell window with the Python interactive prompt. (It’s shown in Figure 4-1.) Yours may be a bit longer. I shrunk mine to keep from wasting paper.
To open the IDLE Shell on Mac: Open a terminal and type IDLE at the prompt. The IDLE Shell window opens.
For the rest of your projects, start up IDLE and use IDLE’s Shell window when you see the ››› prompts, or when I ask you to start a copy of Python I mean to start IDLE and use IDLE’s Shell window.
Type the Hello World! program from Project 2 into the prompt.
You should get a pleasant surprise like the one in Figure 4-2.
IDLE shows you all parts of the program, including Python’s output, in different colors. IDLE gives different colors to keywords (like print), strings (like 'Hello World!'), and numbers. These color cues can be helpful when you’re programming.
In Figure 4-3 the closing parenthesis is still green, not black. This means that Python still thinks it’s part of a string literal. You know then that you have to put in a closing quote. What’s more, when you press Enter, IDLE highlights the error.
In addition to the error notice that you get from the Python interpreter, IDLE gives you visual feedback about where it thinks there’s a problem. Of course, IDLE isn’t always right.
The IDLE Shell window has a couple of tricks that make coding a little easier. Tab completion and command history are two good tricks.
Tab completion is using the Tab key to finish your typing for you. Try it out with these steps:
Type p and press the Tab key. This is tab completion at work!
A drop-down window appears, giving you different options. In Figure 4-4 you can see the window.
Press the arrow key to get to print in the drop-down window.
The p that you typed changes to the word print.
Type ('Hello World!') and then press Enter.
Keep typing to close the drop-down window; don’t press Enter. If you press Enter while you’re there, you’ll muck up the completion. If typing is just too weird for you, press the Tab key twice to accept the highlighted selection. Weird, I know.
Tab completion also works with the names of variables that you’ve already created. Try this example:
Type thi and press the Tab key.
Yes, type only t, h, and i.
The whole variable name should be typed out for you now. Only one variable matches the completion for thi, so you don’t have to choose from a list.
Press Enter.
The code at the current command prompt is copied. If there’s a code block (such as one associated with a conditional statement like if), then the whole code block is also copied.
Try it yourself:
Type print('Hello World!) at the prompt.
Yes, just the one quote. The line is intentionally wrong.
Press Enter.
Python complains about a syntax error, like you see in Figure 4-5.
Press the up arrow key until the cursor is back on the previous line.
You should have to press it three times.
Press Enter.
A copy of the code appears at the interpreter prompt. See the copied line in Figure 4-6.
Insert the closing quote and then press Enter.
Using command line history is often easier than retyping the whole line again. Missing quote marks, misspellings, and bad syntax are cases where it’s good to use.
IDLE’s Editor window is where you’ll spend most of your programming hours. The main thing about the Editor window is that you get to save your typing (unlike the Shell window). You can save your programs and run them without having to retype them every time. (Yay!)
You can open an Editor window through the menu bar in the Shell window.
You get a clean, shiny new window.
This window doesn’t have the interpreter prompt or the message telling you what version of Python you’re using. That’s because it’s not for directly running your code. Rather, it’s for creating and saving your code into a file which can be run and edited later.
Saving your code in a file makes life a lot easier for you, especially as your programs grow larger. However, you don’t get the immediate feedback you do when using the Shell.
Try this:
Look at the window’s title bar.
Right now it’s named Untitled.
Type """This is just a test file""" and press Enter.
This is called a comment, and I explain it in a minute.
Check the title bar again.
It’s now *Untitled*. The stars (asterisks, really, but who asterisked me?) mean that you have unsaved changes in the file.
Type print('Hello World! from the editor') and press Enter.
Unlike in the Shell window, nothing happens. Your Editor window should look like Figure 4-7.
Press the F5 key or choose Run ⇒ Run Module from the menu bar.
F5 is the function key at the top of your keyboard. When you take this step, IDLE says Source Must Be Saved. OK to Save?
Click OK on the dialog box.
A Save As dialog box opens in Windows.
Type test_file.py in the text box marked File Name:.
Remember to add .py to the end of the filename. IDLE won’t do it for you.
Don’t worry about the directory for now, just save it wherever IDLE wants.
Click the Save button.
If you get a dialog box like Figure 4-8, you’ve copied and pasted some quotes (typically from the program Word). If so, your code won’t work. Go back through your code and replace quotes with real single or double quotes. (IDLE may or may not help with a syntax error in this case.)
When you click the Save button, IDLE saves your code into the file with the name you gave it (in this case, test_file.py). Then it runs that file and puts any output in the Shell window. Now the Shell window should look like Figure 4-9.
The file you made in the previous section should look like this:
"""This is just a test file"""
print('Hello World! from the editor')
The first line here is called a comment. It looks like the string literals that you read about in Project 2 — because that’s what it is. When Python sees a string literal in a file it ignores it! This is a good thing because you can communicate messages to your future self through the comments in the program text. In this case, you’re telling yourself that this file is just a test file, so you shouldn’t be too bummed if you mess up.
You have a lot of good reasons to write comments in your code:
Technically, any string literal can be a comment — but it’s better to use literals with triple double quotes """Like this comment""". (Comments are like the basketball player of code: the triple double!) You can also make a comment by using a hash mark: #.
When Python finds a hash, it ignores everything following the hash on the line. Hashes are usually for comments at the end of a line or short comments in the middle of code. They’re faster than a string literal, since you’re only typing one character. However, if you want to use hashes for a comment that runs a couple of lines, you have to type a new hash at the start of each line.
Here is an example of code with both types of comment:
"""This is just a test file"""
print('Hello World! from the editor') # Use # for comments too!
""" You usually use hashes at the end of a line
rather than for a block comment like this one.
"""
###############################################################
# Nevertheless you can still use hashes for block comments
# Especially if you want to have a specific visual effect
###############################################################
print('See that the comments were ignored?') # even this one
The comments inside triple double quotes can go over as many lines as you like; make sure to end with triple double quotes, too. This hashed block is technically four separate comments on consecutive lines.
You might have thought the end of Project 3 was annoying when you had to keep retyping more or less the same code to play the guessing game. Never fear! Now you can save your program into a file and run it from there.
Often when you’re running a program you’ll want to skip a block of code for one reason or another. For example, you might have a problem in one part, but the program goes through another section before it gets there. That other part of the code might take too long to get through or make it tough to understand a problem. Or maybe you want to try a different approach, so you comment out the original code while you test the variation.
IDLE lets you comment out many lines at once. Here’s how:
"""This is a file to use when demonstrating
how to comment out a code block. """
# this section is holding us up for some reason
print('Imagine that instead of these print statements,')
print('there is instead some code which, if it runs')
print('will complicate the process of debugging some later piece')
print('of code. ')
# This is the later section which needs to be debugged
print('Hello World! ')
# imagine there's more program below as well
Select the lines to comment out.
Click and drag with your mouse to select the code, or press Shift while using your arrow keys. See the highlighted code in Figure 4-10.
Choose Format ⇒ Comment Out Region.
Alt+3 and Alt-O also work. After you do that, the selected code should have hash marks in front of it. You can see the results in Figure 4-11.
Now when you run the code, the commented-out sections are skipped. Maybe you found the problem and debugged the block. You can reinstate (convert it from a comment to code) commented-out code with these steps:
Choose Format ⇒ Uncomment Region.
Alt+4 and Alt-O, N also work. Your code is restored to normal.
You’re going to have to change the number of spaces in front of one or more lines of code. It’s common in programming. Moving them in is indenting. Moving them out is dedenting (or deindenting).
For example, if you want to move a print statement from the main part of the program into the code block of a loop, you need to indent it. To move it out of the code block of a loop, you need to deindent it. IDLE has tools to indent and dedent code blocks.
Try those -denting tools:
Start with some code.
Here’s some:
"""This is just a test file"""
DEBUG = True
print('Hello World! from the editor') # Use # for comments too!
""" You usually use hashes at the end of a line
rather than for a block comment like this one.
"""
###############################################################
# Nevertheless you can still use hashes for block comments
# Especially if you want to have a specific visual effect
###############################################################
if DEBUG:
print('I think I need another print statement.')
print('See that the comments were ignored?') # even this one
Select the lines to indent.
Click and drag with your mouse to select the code (the last print statement), or press Shift while using your arrow keys.
Choose Format ⇒ Indent Region.
Ctrl+] also works.
Make sure the code’s indented into a valid code block.
Indentation is meaningful to Python. You’ll get a syntax error if you have the wrong level of indent.
It’s best to use four spaces of indent for each code block level. If you use another number of spaces (2, 6, 8), that’s fine. The important thing is that all the code in the code block must have the same number of spaces.
To go the other way, select the code and choose File ⇒ Dedent Region (or press Ctrl+[).
In this project you