PROJECT 4

Set Up Your Coding Environment

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!)

image

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.

Use the Default Development Environment

An integrated development environment is a kind of word processor for coding.

warning Never use a word processor for coding! Don’t cut and paste from your word processor. Characters that work with Python get replaced with heinous ones that Python can’t handle. For example, something like message = 'Don’t use Word!' should create a string literal. If you copy and paste it from Word into Python, you get a syntax error on the first single quote. That’s because ‘ isn’t the same thing as '. These things — “” — are different from what Python uses: "".

warning The IDLE environment won’t work if you’re using Python on a tablet. Look at an app store for apps that give you a coding environment on your tablet.

Python comes with a code editor called IDLE. The editor has two main parts:

  • The Shell window gives you the Python prompt shown in Figure 4-1.
  • The Editor window lets you save and run your files.
image

Figure 4-1: My IDLE’s shrunken Shell window looks like this.

Start IDLE

In Project 1 you pin IDLE (Python GUI) to the top of your Start menu. It should still be up there.

  1. 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.

    tip 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.

  2. Type the Hello World! program from Project 2 into the prompt.

    You should get a pleasant surprise like the one in Figure 4-2.

image

Figure 4-2: Syntax highlights put your code in different colors.

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.

image

Figure 4-3: IDLE highlights your 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.

Stash Some IDLE Tricks

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

Tab completion is using the Tab key to finish your typing for you. Try it out with these steps:

  1. Start a new line in the Shell window.
  2. 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.

  3. Press the arrow key to get to print in the drop-down window.

    The p that you typed changes to the word print.

  4. Type ('Hello World!') and then press Enter.

    warning 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.

image

Figure 4-4: Press the Tab key to open this drop-down menu.

Tab completion also works with the names of variables that you’ve already created. Try this example:

  1. Start a new line in the Shell window.
  2. Type this_is_a_long_variable_name = 0.
  3. Press Enter.
  4. 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.

image

Figure 4-5: Python’s hissing about an error.

Command history

tip IDLE lets you go back and edit your mistakes using command history. To use command history, follow these steps:

  1. Use the up arrow key to go back to the line you want to run again.
  2. 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.

  3. Use the arrow, Backspace, and Delete keys to edit the line.
  4. Press Enter to run the code.

Try it yourself:

  1. Type print('Hello World!) at the prompt.

    Yes, just the one quote. The line is intentionally wrong.

  2. Press Enter.

    Python complains about a syntax error, like you see in Figure 4-5.

  3. Press the up arrow key until the cursor is back on the previous line.

    You should have to press it three times.

  4. Press Enter.

    A copy of the code appears at the interpreter prompt. See the copied line in Figure 4-6.

  5. Use the arrow keys to go to the end of the line.
  6. Insert the closing quote and then press Enter.

    tip 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.

image

Figure 4-6: Command line history copies lines so you can fix errors.

Use the IDLE Editor Window

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!)

tip Use the Shell window to test a single command or small sections of code. Use the Editor window to create, save, and edit your code when you’re building bigger programs.

You can open an Editor window through the menu bar in the Shell window.

  • In Windows, choose File ⇒ New File. Or, type Ctrl+N in the Shell window.
  • On a Mac, in the Shell window, choose File ⇒ New Window. Or, select Cmd+N 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:

  1. Look at the window’s title bar.

    Right now it’s named Untitled.

  2. Type """This is just a test file""" and press Enter.

    This is called a comment, and I explain it in a minute.

  3. Check the title bar again.

    tip It’s now *Untitled*. The stars (asterisks, really, but who asterisked me?) mean that you have unsaved changes in the file.

  4. 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.

  5. 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?

  6. Click OK on the dialog box.

    A Save As dialog box opens in Windows.

  7. Type test_file.py in the text box marked File Name:.

    tip 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.

  8. 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.

image

Figure 4-7: This program is in the IDLE Editor window.

image

Figure 4-8: Encoding dialog box. If you see this, you’ve done something wrong.

image

Figure 4-9: When you run a program in the Editor window (top), the Shell window restarts (bottom).

tip You can run the program again by pressing F5 as many times as you want. Each time the Shell window will restart. When the Shell restarts, you lose the values of any variables that you had earlier typed into the Shell. You also lose tab completion of those variable names.

Write Comments in Your Files

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:

  • As an explanation. Whenever you create a new Python file, write a short explanation of what the code’s supposed to do. Don’t repeat what the code is doing. Summarize what the code is for. What do you want to achieve? So, in the code a = a+1 # adding 1 to a the comment is pointless because any fool can see that the code is adding 1 to a. You’d generally not include a comment here unless there was a reason that is not clear from the code. For example: a = a+1 # Changing a causes the data to be refreshed in the next code block.
  • As a memory aid. When you’re first writing your code you’re very close to it. You’re familiar with it. You understand why you’ve put what you’ve put where and why. As time goes by, you will forget why you put that piece of code somewhere. It’s a lot easier to read a description than work it out later.
  • As a means of communication. When you give your code to someone else, an English explanation of what the code does is even more important. Comments allow you to collaborate (work together) better with others. If you want to work as part of a programming team, you’d better have good comments in your code.
  • As a debugging aid. If there’s a problem with your code, someone will need to go in and fix it, and it may not be you. Again, having an English explanation of what’s going on is a big help.
  • Because it’s good for you. Like vegetables, only tastier.

Insert Hash Comments

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.

Save Your Shell Contents

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.

warning You can choose File ⇒ Save from IDLE’s Shell window to save the contents of the interpreter window. The saved parts include the opening version number notice and the interactive session at the Shell, which means you can’t run the file as a Python program later. You only save the Shell session if there’s output in your Shell that you want to keep.

Comment Out Code

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.

tip If you want to temporarily stop code from executing, don’t delete the code from the file. A better approach is to comment out the code. Comment out code by putting a hash in front of each line of code.

IDLE lets you comment out many lines at once. Here’s how:

  1. Start with some code. Oh, here’s one I prepared earlier:

    """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

  2. 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.

  3. 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.

image

Figure 4-10: Select the code that you want commented out.

image

Figure 4-11: Hashes are added after you comment out code.

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:

  1. Select the lines to be reinstated.
  2. Choose Format ⇒ Uncomment Region.

    Alt+4 and Alt-O, N also work. Your code is restored to normal.

Indent and Dedent Your Code

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:

  1. 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

  2. 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.

  3. Choose Format ⇒ Indent Region.

    Ctrl+] also works.

  4. 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.

    remember 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+[).

Summary

In this project you

  • Started and stopped IDLE.
  • Checked out IDLE’s Shell window and Editor window.
  • Included comments in your code.
  • Commented out code, and commented it back in.
  • Indented and dedented (deindented) a code block.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.21.115