Книга: Practical Programming, Fourth Edition
Назад: Designing New Functions: A Recipe
Дальше: Omitting a return Statement: None

Writing and Running a Program

So far, you have used the shell to investigate Python. As you have seen, the shell displays 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.)

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

Here is a program that was written 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 to that function, which convert three different Fahrenheit temperatures to their Celsius equivalents.

 def​ ​convert_to_celsius​(fahrenheit: float) -> float:
 """Return the number of Celsius degrees equivalent to fahrenheit degrees.
 
  >>> convert_to_celsius(75)
  23.88888888888889
  """
 
 return​ (fahrenheit - 32.0) * 5.0 / 9.0
 
 convert_to_celsius(80)
 convert_to_celsius(78.8)
 convert_to_celsius(10.4)

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

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

 Python 3.14.0b4 (main, Jul 9 2025, 09:00:21) [GCC 11.4.0] on linux
 Enter "help" below or click "Help" above for more information.
 >>>
 ===================== RESTART; /tmp/temperature_program.py ==================
 >>>

Notice that no values are shown, unlike in , when you typed the equivalent code into the shell. To have a program print the value of an expression, use the built-in function print. Here is the same program, but with calls to the print function.

 def​ ​convert_to_celsius​(fahrenheit: float) -> float:
 """Return the number of Celsius degrees equivalent to fahrenheit
  degrees.
 
  >>> convert_to_celsius(75)
  23.88888888888889
  """
 
 return​ (fahrenheit - 32.0) * 5.0 / 9.0
 
 print​(convert_to_celsius(80))
 print​(convert_to_celsius(78.8))
 print​(convert_to_celsius(10.4))

And here is what happens when you run this program:

 Python 3.14.0b4 (main, Jul 9 2025, 09:00:21) [GCC 11.4.0] on linux
 Enter "help" below or click "Help" above for more information.
 >>>
 ===================== RESTART; /tmp/temperature_program.py ==================
 26.666666666666668
 26.0
 -12.0
 >>>
Назад: Designing New Functions: A Recipe
Дальше: Omitting a return Statement: None