Up to now, we’ve been writing single Python statements and running them at the interactive command line. While that’s useful for learning about Python functions, it quickly becomes tiresome when you need to solve problems that require many lines of Python code.
Thus we turn to writing programs (also known as scripts). Programs are just text files containing a collection of Python commands. When you run (or execute) a program, Python performs each statement in the file one after the other.
In this chapter, we’ll learn how to write and run programs in IDLE and from the command line. We’ll see how to get keyboard input from the user and print strings to the screen.
This is just the first step in writing Python programs. In the following chapters, we’ll gradually explore more features for writing programs, including if statements, loops, and functions.
You should make an effort to type the code yourself, since it is an excellent way to get used to the various rules of writing Python. For larger programs, you can download the code from this book’s Web site: http://pythonintro.googlecode.com.
IDLE comes with a Python-aware text editor. The best way to learn about it is to write a simple program.
Procedure 3.1. To write a new program in IDLE:
Launch IDLE.
Choose File > New Window.
A blank editor window should pop up.
To test it, enter the following into it:
print('Welcome to Python!')
Save your program by choosing File > Save. Save it in your Python programs folder with the name welcome.py
; the .py
at the end indicates that this is a Python file.
Run your program by choosing Run > Run Module.
A Python shell should appear, and you should see Welcome to Python! within it.
When you start to get more familiar with the IDLE editor, you may want to start using some of the key commands listed in Table 3.1. They can really speed up your editing.
Create a special folder called, say, python on your computer’s Desktop to store all your Python programs. Never save them in the Python directory; other-wise, you run the risk of accidentally overwriting one of Python’s core files.
You must type in Python programs exactly as you see them, character for character. A single wrong character—an extra space, an l
instead of a 1
—can cause errors.
If you do see an error when you run your program, go back to the editor window and carefully check that your program was typed correctly, character for character.
Another common way to run a Python program is from the command line. For example, to run welcome.py
, you can open a command-line window and run it by typing python
, followed by the filename:
C:> python welcome.py Welcome to Python!
To run a program from the command line:
Type the following:
C:> python file name.py.
You can also just call Python without a program and get a bare-bones (but still quite useful) version of the interactive interpreter.
To call Python from the command line:
Type the following:
C:> python Python 3.0b2 (r30b2:65106, Jul 18 2008, 18:44:17) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>
Calling Python from the command line is most commonly used when you run Python scripts as parts of other programs.
The easiest way to open a command window in Windows is to click the Start menu; then click Run, and type cmd
and press Return. This should give you a command-line window.
Running Python from the command line is similar on Mac and Linux systems: run a command shell (the exact details for doing this differ from system to system, but try browsing programs available through menus on your Desktop), and then type python
followed by the name of the program you want to run.
One annoyance with running Python from the command line is that it is often necessary to configure environment variables, in particular your system’s path variable, so that your system knows where to find Python on your computer. The details are finicky and system specific, and are beyond the scope of this book. However, it is not hard to find detailed instructions online if you want to set this up. For instance, just type set windows path into your favorite Web search engine. Take care when you are modifying environment variables: If you are not sure exactly what you are doing, it is quite possible to “break” your system so that programs no longer run correctly. In that case, your best option is usually to start over and reinstall Python.
We often refer to the statements inside a Python program as source code, and so a program file is sometimes called a source code file, or source file. By convention, all Python source code files end with the extension .py
. This makes it easy for people and programs to see at a glance that the file contains Python source code.
When you run a .py
file, Python automatically creates a corresponding .pyc
file (Figure 3.1). A .pyc
file contains object code, or compiled code. Object code is essentially a Python-specific language that represents your Python source code in a way that is easier for the computer to run efficiently. It is not meant for humans to read, and so most of the time you should just ignore the .pyc
files that start to appear.
Figure 3.1. Python consists of three major components: an interpreter for running single statements; a compiler for converting .py
files to .pyc
files; and a virtual machine for running .pyc
files. Note that IDLE is not strictly part of Python; it is a separate application that sits on top of Python to make it easier to use.
A Python program runs using a special piece of software called a virtual machine. This is essentially a software simulation of a computer designed just to run Python, and it is part of the reason why many .pyc
files can run on different computer systems without any change.
You will rarely, if ever, have to worry about .pyc
files. Python automatically creates them when needed, and also automatically updates them when you change the corresponding .py
files. Don’t delete, rename, or modify the .pyc
files!
Since they are meant to be read only by the computer, .pyc
files are not stored as text files. If you try to view a .pyc
file in a text editor, you’ll see nothing but junk characters.
Reading a string from the keyboard is one of the most basic ways of getting information from a user. For example, consider this simple program:
# name.py
name = input('What is your first name? ')
print('Hello ' + name.capitalize() + '!')
To run this in IDLE, open name.py
in an IDLE window, and then to run it press F5 (or, equivalently, choose Run > Run Module).
You should see this in the window that appears:
What is your first name? jack
Hello Jack!
You, the user, must type in the name (in this case the string 'jack'
).
Let’s look carefully at each line of the program. The first line is a source code comment, or comment for short. A comment is just a note to the programmer, and Python ignores it. Python comments always start with a #
symbol and continue to the end of the line. This particular comment tells you that the program is stored in a file called name.py
.
The second line calls the input
function, which is the standard built-in function for reading strings from the keyboard. When it runs, the prompt 'What is your name?'
appears in the output window, followed by a blinking cursor. The program waits until the user enters a string and presses Enter. The input
function evaluates to whatever string the user enters, and so the variable name
ends up labeling the string that the user types in.
The third and final line of the program displays a greeting. The function name.capitalize()
ensures that the first character of the string is uppercase and the remaining characters are lowercase. This way, if the user happens to enter a name that isn’t correctly capitalized, Python will correct it.
Don’t forget to use the dir
function to see what functions are available for strings. For example, typing dir('')
at IDLE’s interactive command line lists all of the string functions.
If you run name.py
with a number of sample strings, you’ll soon discover that entering a name like 'Jack Aubrey'
will actually uncapitalize the last name: 'Hello Jack aubrey!'
. That’s because the capitalize
function is very simpleminded—it knows nothing about words or spaces. Properly capitalizing a string of words requires some more advanced programming that we will see later in this book.
Another common and useful trick when reading strings from the keyboard is to use the strip()
function to remove any leading/trailing whitespace characters. For instance:
>>> ' oven '.strip() 'oven'
The call to strip()
is often put directly in the input statement like this:
name = input('Enter age: ').strip()
The input
function only returns strings, so if you need a number data type (for example, to do arithmetic), you must use one of Python’s numeric conversion functions. For example, consider this program:
# age.py age = input('How old are you today? ') age10 = int(age) + 10 print('In 10 years you will be ' + str(age10) + ' years old.')
Suppose the user types in 22
in response to this program. Then the variable age
labels the string '22'
—Python does not automatically convert strings that look like numbers to integer or float values. If you want to do arithmetic with a string, you must first convert it to a number using either int(s)
(if you want an integer) or float(s)
(if you want a float).
The one final trick to notice is that in the print
statement, it’s necessary to convert the variable age10
(which labels an integer) back into a string so that it can be printed. If you forget this conversion, Python issues an error saying it can’t add numbers and strings.
The print
statement is the standard built-in function for printing strings to the screen. As we will see, it is extremely flexible and has many useful features for formatting strings and numbers in just the right way.
You can pass any number of strings to print
:
>>> print('jack', 'ate', 'no', 'fat') jack ate no fat
By default, it prints out each string in the standard output window, separating the strings with a space. You can easily change the string separator like this:
>>> print('jack', 'ate', 'no', 'fat',
sep = '.')
jack.ate.no.fat
By default, a string ends with a newline character:
. A newline character causes the cursor to move to the next line when the string is printed, and so, by default, you can’t print anything on the same line after calling print
:
# jack1.py print('jack ate ') print('no fat')
This prints two lines of text:
jack ate no fat
To put all the text on a single line, you can specify the end character of the first line to be the empty string:
# jack2.py print('jack ate ', end = '') print('no fat')
The print
function is one of the major differences between Python 2 and Python 3. Before Python 3, print
was not actually a function, but instead was a built-in part of the language. The one advantage of this was that you didn’t have to type the brackets—for example, you would type print 'jack ate no fat'
. However, despite that small convenience, print
’s not being a function made it very difficult to change the default separator and ending strings, which is often necessary in more advanced programs.
Another difference between Python 2 and 3 is that Python 3’s input
function was called raw_input
in Python 2. Python 2 also had a function called input
, but it evaluated the string that the user entered, which was occasionally handy. There is no equivalent of the Python 2 input
function in Python 3, although you can easily simulate it by typing eval(input(prompt))
. For example:
>>> eval(input('? ')) ? 4 + 5 * 6 34
We’ve already seen source code comments used to specify the name of a file. But comments are useful for any kind of note that you might want to put into a program, such as documentation, reminders, explanations, or warnings. Python ignores all comments, and they are only there to be read by you and other programmers who might read the source code.
Here’s a sample program that shows some more uses of comments:
# coins_short.py # This program asks the user how many # coins of various types they have, # and then prints the total amount # of money in pennies. # get the number of nickels, dimes, # and quarters from the user n = int(input('Nickels? ')) d = int(input('Dimes? ')) q = int(input('Quarters? ')) # calculate the total amount of money total = 5 * n + 10 * d + 25 * q # print the results print() # prints a blank line print(str(total) + ' cents')
As you start to write more programs, you will soon notice that they tend to follow a common structure. Typically, programs are organized as in Figure 3.2: They have an input part, a processing part, and an output part.
For the small programs that we are starting out with, this structure is usually obvious and does not require much thought. But as your programs get bigger and more complex, it is easy to lose sight of this overall structure, which often results in messy code that is hard to understand.
Thus, indicating in comments what parts are for input, processing, and output is a good habit to get into. It helps clarify the different tasks your program performs; and, when we start writing functions, it provides a natural way of dividing up your programs into sensible functions.
18.189.195.229