Writing and Running a Program

So far, we have used the shell to investigate Python. As you have seen, the shell will show you the result of evaluating an expression:

 >>>​​ ​​3​​ ​​+​​ ​​5​​ ​​/​​ ​​abs(-2)
 5.5

In a program that is supposed to interact with a human, showing the result of every expression is probably not desirable behavior. (Imagine if your web browser showed you the result of every calculation it performed.)

How Does a Computer Run a Python Program?, explained that in order to save code for later use, you can put it in a file with a .py extension. You can then tell Python to run the code in that file rather than type commands in at the interactive prompt.

Here is a program that we wrote using IDLE and saved in a file called temperature.py. This program consists of a function definition for convert_to_celsius (from earlier in the chapter) and three calls on that function that convert three different Fahrenheit temperatures to their Celsius equivalents.

images/functions/temperature_noprint.png

Notice that there is no >>> prompt. This never appears in a Python program; it is used exclusively in the shell.

Now open IDLE, select FileNew Window, and type this program in. (Or download the code from the book website and open the file.)

To run the program in IDLE, select RunRun Module. This will open the Python shell and show the results of running the program. Here is our result. (The line containing RESTART is letting us know that the shell has restarted, wiping out any previous work done in the shell.)

images/functions/temperature_noprint_out.png

Notice that no values are shown, unlike in Defining Our Own Functions, when we typed the equivalent code into the shell. In order to have a program print the value of an expression, we use built-in function print. Here is the same program but with calls on function print.

images/functions/temperature_print.png

And here is what happens when we run this program:

images/functions/temperature_print_out.png
..................Content has been hidden....................

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