1.6.The Magic of Python 11 Do you see what this does?The two print statements from the hello function are executed in sequence. You may be wondering about the parentheses in the definition and use of hello.Commands can have changeable parts called parameters that are placed within the parentheses.Let's look at an example of a customized greeting using a parameter.First the definition: >>def greet(person): print "Hello",person print "How are you?" Now we can use our customized greeting. >>greet("John") Hello John How are you? >>greet("Emily") Hello Emily How are you? >>> Can you see what is happening here?When we use greet we can send different names to customize the result.We will discuss parameters in detail later on.For the time being,our functions will not use parameters,so the parentheses will be empty,but you still need to include them when defining and using functions. One problem with entering functions interactively at the Python prompt like this is that the definitions go away when we quit Python.If we want to use them again the next time,we have to type them all over again.Programs are usually created by typing definitions into a separate file called a module or script.This file is saved on a disk so that it can be used over and over again. A module file is just a text file,and you can create one using any program for editing text,like a notepad or word processor program(provided you save your program as a"plain text"file).A special type of program known as a pro- gramming environment simplifies the process.A programming environment is specifically designed to help programmers write programs and includes features such as automatic indenting,color highlighting,and interactive development. The standard Python distribution includes a programming environment called IDLE that you may use for working on the programs in this book. Let's illustrate the use of a module file by writing and running a complete program.Our program will illustrate a mathematical concept known as chaos
1.6. The Magic of Python 11 Do you see what this does? The two print statements from the hello function are executed in sequence. You may be wondering about the parentheses in the definition and use of hello. Commands can have changeable parts called parameters that are placed within the parentheses. Let's look at an example of a customized greeting using a parameter. First the definition: >» def greet (person) : print "Hello", person print "How are you?" Now we can use our customized greeting. >» greet ("John") Hello John How are you? >» greet ("Emily") Hello Emily How are you? >» Can you see what is happening here? When we use greet we can send different names to customize the result. We will discuss parameters in detail later on. For the time being, our functions will not use parameters, so the parentheses will be empty, but you still need to include them when defining and using functions. One problem with entering functions interactively at the Python prompt like this is that the definitions go away when we quit Python. If we want to use them again the next time, we have to type them all over again. Programs are usually created by typing definitions into a separate file called a module or script. This file is saved on a disk so that it can be used over and over again. A module file is just a text file, and you can create one using any program for editing text, like a notepad or word processor program (provided you save your program as a "plain text" file). A special type of program known as a programming environment simplifies the process. A programming environment is specifically designed to help programmers write programs and includes features such as automatic indenting, color highlighting, and interactive development. The standard Python distribution includes a programming environment called IDLE that you may use for working on the programs in this book. Let's illustrate the use of a module file by writing and running a complete program. Our program will illustrate a mathematical concept known as chaos
12 Chapter 1.Computers and Programs Here is the program as we would type it into IDLE or some other editor and save in a module file: File:chaos.py A simple program illustrating chaotic behavior. def main(): print "This program illustrates a chaotic function" x input("Enter a number between 0 and 1:" for i in range(10): x=3.9*X*(1-x) print x main() This file should be saved with the name chaos.py.The.py extension in- dicates that this is a Python module.You can see that this particular example contains lines to define a new function called main.(Programs are often placed in a function called main.)The last line of the file is the command to invoke this function.Don't worry if you don't understand what main actually does;we will discuss it in the next section.The point here is that once we have a program in a module file,we can run it any time we want. This program can be run in a number of different ways that depend on the actual operating system and programming environment that you are using.If you are using a windowing system,you can run a Python program by clicking (or double-clicking)on the module file's icon.In a command line situation,you might type a command like python chaos.py.If you are using IDLE(or another programming environment)you can run a program by opening it in the editor and then selecting a command like import,run,or execute. One method that should always work is to start the Python interpreter and then import the file.Here is how that looks: >>import chaos This program illustrates a chaotic function Enter a number between 0 and 1:.25 0.73125 0.76644140625 0.698135010439 0.82189581879 0.570894019197
12 Chapter 1. Computers and Programs Here is the program as we would type it into IDLE or some other editor and save in a module file: # File: chaos. py # A simple program illustrating chaotic behavior. def mainO : print "This program illustrates a chaotic function" X = input ("Enter a number between cind 1: ") for i in raiige(lO): X = 3.9 * X * (1 - x) print X mainO This file should be saved with the name chaos. py. The .py extension in- dicates that this is a Python module. You can see that this particular example contains lines to define a new function called main. (Programs are often placed in a function called main.) The last line of the file is the command to invoke this function. Don't worry if you don't understand what main actually does; we will discuss it in the next section. The point here is that once we have a program in a module file, we can run it any time we want. This program can be run in a number of different ways that depend on the actual operating system and programming environment that you are using. If you are using a windowing system, you can run a Python program by clicking (or double-clicking) on the module file's icon. In a command line situation, you might type a command like python chaos . py. If you are using IDLE (or another programming environment) you can run a program by opening it in the editor and then selecting a command like import, run, or execute. One method that should always work is to start the Python interpreter and then import the file. Here is how that looks: >>> import chaos This program illustrates a chaotic function Enter a number between and 1 : .25 0.73125 0.76644140625 0.698135010439 0.82189581879 0.570894019197
1.6.The Magic of Python 13 0.955398748364 0.166186721954 0.540417912062 0.9686289303 0.118509010176 >>> Typing the first line import chaos tells the Python interpreter to load the chaos module from the file chaos.py into main memory.Notice that I did not include the.py extension on the import line;Python assumes the module will have a .py extension. As Python imports the module file,each line executes.It's just as if we had typed them one-by-one at the interactive Python prompt.The def in the module causes Python to create the main function.When Python encounters the last line of the module,the main function is invoked,thus running our program. The running program asks the user to enter a number between 0 and 1(in this case,I typed".25")and then prints out a series of 10 numbers. When you first import a module file in this way,Python creates a companion file with a.pyc extension.In this example,Python creates another file on the disk called chaos.pyc.This is an intermediate file used by the Python inter- preter.Technically,Python uses a hybrid compiling/interpreting process.The Python source in the module file is compiled into more primitive instructions called byte code.This byte code (the.pyc)file is then interpreted.Having a pyc file available makes importing a module faster the second time around. However,you may delete the byte code files if you wish to save disk space; Python will automatically recreate them as needed. A module needs to be imported into a session only once.After the mod- ule has been loaded,we can run the program again by asking Python to exe- cute the main command.We do this by using a special dot notation.Typing chaos.main()tells Python to invoke the main function in the chaos module. Continuing with our example,here is how it looks when we rerun the program with.26 as the input: >>>chaos.main() This program illustrates a chaotic function Enter a number between 0 and 1:.26 0.75036 0.73054749456 0.767706625733
1.6. The Magic of Python 13 0.955398748364 0.166186721954 0.540417912062 0.9686289303 0.118509010176 >» Typing the first line import chaos tells the Python interpreter to load the chaos module from the file chaos .py into main memory. Notice that I did not include the .py extension on the import line; Python assumes the module will have a . py extension. As P5^hon imports the module file, each line executes. It's just as if we had typed them one-by-one at the interactive Python prompt. The def in the module causes Python to create the main function. When Python encounters the last line of the module, the main function is invoked, thus running our program. The running program asks the user to enter a number between and 1 (in this case, I typed ".25") and then prints out a series of 10 numbers. when you first import a module file in this way. Python creates a companion file with a . pyc extension. In this example. Python creates another file on the disk called chaos. pyc. This is an intermediate file used by the Python interpreter. Technically, Python uses a hybrid compiling/interpreting process. The Python source in the module file is compiled into more primitive instructions called byte code. This byte code (the .pyc) file is then interpreted. Having a .pyc file available makes importing a module faster the second time around. However, you may delete the byte code files if you wish to save disk space; Python will automatically recreate them as needed. A module needs to be imported into a session only once. After the module has been loaded, we can run the program again by asking Python to exe- cute the main command. We do this by using a special dot notation. Typing chaos. main tells Python to invoke the main function in the chaos module. Continuing with our example, here is how it looks when we rerun the program with .26 as the input: >» chaos . main ( ) This program illustrates a chaotic function Enter a number between and 1 : .26 0.75036 0.73054749456 0.767706625733
14 Chapter 1.Computers and Programs 0.6954993339 0.825942040734 0.560670965721 0.960644232282 0.147446875935 0.490254549376 0.974629602149 >>> 1.7 Inside a Python Program The output from the chaos program may not look very exciting,but it illustrates a very interesting phenomenon known to physicists and mathematicians.Let's take a look at this program line by line and see what it does.Don't worry about understanding every detail right away;we will be returning to all of these ideas in the next chapter. The first two lines of the program start with the character: File:chaos.py A simple program illustrating chaotic behavior. These lines are called comments.They are intended for human readers of the program and are ignored by Python.The Python interpreter always skips any text from the pound sign (#)through the end of a line. The next line of the program begins the definition of a function called main: def main(): Strictly speaking,it would not be necessary to create a main function.Since the lines of a module are executed as they are loaded,we could have written our program without this definition.That is,the module could have looked like this: File:chaos.py A simple program illustrating chaotic behavior. print "This program illustrates a chaotic function" x input("Enter a number between 0 and 1:" for i in range(10): X=3.9*x*(1-x) print x
14 Chapter 1. Computers and Programs 0.6954993339 0.825942040734 0.560670965721 0.960644232282 0.147446875935 0.490254549376 0.974629602149 >» 1.7| Inside a Python Program The output from the chaos program may not look very exciting, but it illustrates a very interesting phenomenon known to physicists and mathematicians. Let's take a look at this program line by line and see what it does. Don't worry about understanding every detail right away; we will be returning to all of these ideas in the next chapter. The first two lines of the program start with the # character: # File: chaos. py # A simple program illustrating chaotic behavior. These lines are called comments. They are intended for human readers of the program and are ignored by Python. The Python interpreter always skips any text from the pound sign (#) through the end of a line. The next line of the program begins the definition of a function called main: def mainO : Strictly speaking, it would not be necessary to create a main function. Since the lines of a module are executed as they are loaded, we could have written our program without this definition. That is, the module could have looked like this: # File: chaos. py # A simple program illustrating chaotic behavior. print "This program illustrates a chaotic function" X = input ("Enter a number between smd 1: ") for i in range (10) : X = 3.9 * X * (1 - x) print X
1.7.Inside a Python Program 15 This version is a bit shorter,but it is customary to place the instructions that comprise a program inside of a function called main.One immediate benefit of this approach was illustrated above;it allows us to run the program by simply invoking chaos.main().We don't have to reload the module from the file in order to run it again,which would be necessary in the main-less case. The first line inside of main is really the beginning of our program. print "This program illustrates a chaotic function" This line causes Python to print a message introducing the program when it runs. Take a look at the next line of the program: x input("Enter a number between 0 and 1:" Here x is an example of a variable.A variable is used to give a name to a value so that we can refer to it at other points in the program.The entire line is an input statement.When Python gets to this statement,it displays the quoted message Enter a number between 0 and 1:and then pauses,waiting for the user to type something on the keyboard and press the <Enter>key.The value that the user types in is then stored as the variable x.In the first example shown above,the user entered.25,which becomes the value of x. The next statement is an example of a loop. for i in range(10): A loop is a device that tells Python to do the same thing over and over again.This particular loop says to do something 10 times.The lines indented underneath the loop heading are the statements that are done 10 times.These form the body of the loop. X=3.9*X*(1-x) print x The effect of the loop is exactly the same as if we had written the body of the loop 10 times: x=3.9*x*(1-x) print x x=3.9*x*(1-x) print x x=3.9*X*(1-x)
1.7. Inside a Python Program 15 This version is a bit shorter, but it is customary to place the instructions that comprise a program inside of a function called main. One immediate benefit of this approach was illustrated above; it allows us to run the program by simply invoking chaos. main (). We don't have to reload the module from the file in order to run it again, which would be necessary in the main-less case. The first line inside of main is really the beginning of our program. print "This program illustrates a chaotic function" This line causes Python to print a message introducing the program when it runs.Take a look at the next line of the program: X = input ("Enter a number between and 1: ") Here x is an example of a variable. A variable is used to give a name to a value so that we can refer to it at other points in the program. The entire Hne is an input statement. When Python gets to this statement, it displays the quoted message Enter a number between and 1 : and then pauses, waiting for the user to type something on the keyboard and press the <Enter> key. The value that the user types in is then stored as the variable x. In the first example shown above, the user entered . 25, which becomes the value of x. The next statement is an example of a loop. for i in range (10): A loop is a device that tells Python to do the same thing over and over again. This particular loop says to do something 10 times. The lines indented underneath the loop heading are the statements that are done 10 times. These form the body of the loop. X = 3.9 * X * (1 - x) print X The effect of the loop is exactly the same as if we had written the body of the loop 10 times: X = 3.9 * X * (1 -- x) print X X = 3.9 * X * (1 -- x) print X X = 3.9 * X * (1 -- x)