2.3.ELEMENTS OF PROGRAMS 15 What is the Celsius temperature?100 The temperature is 212.0 degrees fahrenheit. You can see that Suzie used the values of 0 and 100 to test her program.It looks pretty good,and she is satisfied with her solution.Apparently,no debugging is necessary. 2.3 Elements of Programs Now that you know something about the programming process,you are almost ready to start writing programs on your own.Before doing that,though,you need a more complete grounding in the fundamentals of Python. The next few sections will discuss technical details that are essential to writing correct programs.This material can seem a bit tedious,but you will have to master these basics before plunging into more interesting waters. 2.3.1 Names You have already seen that names are an important part of programming.We give names to modules(e.g., convert)and to the functions within modules(e.g.,main).Variables are used to give names to values(e.g., celsius and fahrenheit).Technically,all these names are called identifiers.Python has some rules about how identifiers are formed.Every identifier must begin with a letter or underscore(the""character) which may be followed by any sequence of letters,digits,or underscores.This implies that a single identifier cannot contain any spaces. According to these rules,all of the following are legal names in Python: X celsius spam spam2 SpamAndEggs Spam and Eggs Identifiers are case-sensitive,so spam,Spam,sPam,and SPAM are all different names to Python.For the most part,programmers are free to choose any name that conforms to these rules.Good programmers always try to choose names that describe the thing being named. One other important thing to be aware of is that some identifiers are part of Python itself.These names are called reserved words and cannot be used as ordinary identifiers.The complete list of Python reserved words is shown in Table 2.1. and del for IS raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print Table 2.1:Python Reserved Words. 2.3.2 Expressions Programs manipulate data.The fragments of code that produce or calculate new data values are called expressions.So far our program examples have dealt mostly with numbers,so I'll use numeric data to illustrate expressions
2.3. ELEMENTS OF PROGRAMS 15 What is the Celsius temperature? 100 The temperature is 212.0 degrees fahrenheit. You can see that Suzie used the values of 0 and 100 to test her program. It looks pretty good, and she is satisfied with her solution. Apparently, no debugging is necessary. 2.3 Elements of Programs Now that you know something about the programming process, you are almost ready to start writing programs on your own. Before doing that, though, you need a more complete grounding in the fundamentals of Python. The next few sections will discuss technical details that are essential to writing correct programs. This material can seem a bit tedious, but you will have to master these basics before plunging into more interesting waters. 2.3.1 Names You have already seen that names are an important part of programming. We give names to modules (e.g., convert) and to the functions within modules(e.g., main). Variables are used to give names to values (e.g., celsius and fahrenheit). Technically, all these names are called identifiers. Python has some rules about how identifiers are formed. Every identifier must begin with a letter or underscore (the “ ” character) which may be followed by any sequence of letters, digits, or underscores. This implies that a single identifier cannot contain any spaces. According to these rules, all of the following are legal names in Python: x celsius spam spam2 SpamAndEggs Spam_and_Eggs Identifiers are case-sensitive, so spam, Spam, sPam, and SPAM are all different names to Python. For the most part, programmers are free to choose any name that conforms to these rules. Good programmers always try to choose names that describe the thing being named. One other important thing to be aware of is that some identifiers are part of Python itself. These names are called reserved words and cannot be used as ordinary identifiers. The complete list of Python reserved words is shown in Table 2.1. and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print Table 2.1: Python Reserved Words. 2.3.2 Expressions Programs manipulate data. The fragments of code that produce or calculate new data values are called expressions. So far our program examples have dealt mostly with numbers, so I’ll use numeric data to illustrate expressions
16 CHAPTER 2.WRITING SIMPLE PROGRAMS The simplest kind of expression is a literal.A literal is used to indicate a specific value.In chaos.py you can find the numbers 3.9 and 1.The convert.py program contains 9.0,5.0,and 32.These are all examples of numeric literals,and their meaning is obvious:32 represents,well,32. A simple identifier can also be an expression.We use identifiers as variables to give names to values. When an identifier appears in an expression,this value is retrieved to provide a result for the expression. Here is an interaction with the Python interpreter that illustrates the use of variables as expressions. >>>x=5 >>>X 5 >>print x 5 >>print spam Traceback (innermost last): File "<pyshell#34>",line 1,in print spam NameError:spam >>> First the variable x is assigned the value 5(using the numeric literal 5).The next line has Python evaluate the expression x.Python spits back 5,which is the value that was just assigned to x.Of course,we get the same result when we put x in a print statement.The last example shows what happens when we use a variable that has not been assigned a value.Python cannot find a value,so it reports a Name Error.This says that there is no value with that name.A variable must always be assigned a value before it can be used in an expression. More complex and interesting expressions can be constructed by combining simpler expressions with operators.For numbers,Python provides the normal set of mathematical operations:addition,subtraction, multiplication,division,and exponentiation.The corresponding Python operators are:+,-,*/and * Here are some examples of complex expressions from chaos.py and convert.py 3.9*x*(1-) 9.0/5.0*ce1sius+32 Spaces are irrelevant within an expression.The last expression could have been written 9.0/5.0*celsius+32 and the result would be exactly the same.Usually it's a good idea to place some spaces in expressions to make them easier to read. Python's mathematical operators obey the same rules of precedence and associativity that you learned in your math classes,including using parentheses to modify the order of evaluation.You should have lit- tle trouble constructing complex expressions in your own programs.Do keep in mind that only the round parentheses are allowed in expressions,but you can nest them if necessary to create expressions like this ((x1-x2)/2*n)+(spam/k**3) If you are reading carefully,you may be curious why,in her temperature conversion program,Suzie Programmer chose to write 9.0/5.0 rather than 9/5.Both of these are legal expressions,but they give different results.This mystery will be discussed in Chapter 3.If you can't stand the wait,try them out for yourself and see if you can figure out what's going on. 2.4 Output Statements Now that you have the basic building blocks,identifier and expression,you are ready for a more complete description of various Python statements.You already know that you can display information on the screen using Python's print statement.But what exactly can be printed?Python,like all programming languages, has a precise set ofrules for the syntax (form)and semantics(meaning)ofeach statement.Computer scientists have developed sophisticated notations called meta-languages for describing programming languages.In this book we will rely on a simple template notation to illustrate the syntax of statements. Here are the possible forms of the print statement:
16 CHAPTER 2. WRITING SIMPLE PROGRAMS The simplest kind of expression is a literal. A literal is used to indicate a specific value. In chaos.py you can find the numbers 3.9 and 1. The convert.py program contains 9.0, 5.0, and 32. These are all examples of numeric literals, and their meaning is obvious: 32 represents, well, 32. A simple identifier can also be an expression. We use identifiers as variables to give names to values. When an identifier appears in an expression, this value is retrieved to provide a result for the expression. Here is an interaction with the Python interpreter that illustrates the use of variables as expressions. >>> x = 5 >>> x 5 >>> print x 5 >>> print spam Traceback (innermost last): File "<pyshell#34>", line 1, in ? print spam NameError: spam >>> First the variable x is assigned the value 5 (using the numeric literal 5). The next line has Python evaluate the expression x. Python spits back 5, which is the value that was just assigned to x. Of course, we get the same result when we put x in a print statement. The last example shows what happens when we use a variable that has not been assigned a value. Python cannot find a value, so it reports a Name Error. This says that there is no value with that name. A variable must always be assigned a value before it can be used in an expression. More complex and interesting expressions can be constructed by combining simpler expressions with operators. For numbers, Python provides the normal set of mathematical operations: addition, subtraction, multiplication, division, and exponentiation. The corresponding Python operators are: +, -, *, /, and **. Here are some examples of complex expressions from chaos.py and convert.py 3.9 * x * (1 - x) 9.0 / 5.0 * celsius + 32 Spaces are irrelevant within an expression. The last expression could have been written 9.0/5.0*celsius+32 and the result would be exactly the same. Usually it’s a good idea to place some spaces in expressions to make them easier to read. Python’s mathematical operators obey the same rules of precedence and associativity that you learned in your math classes, including using parentheses to modify the order of evaluation. You should have little trouble constructing complex expressions in your own programs. Do keep in mind that only the round parentheses are allowed in expressions, but you can nest them if necessary to create expressions like this. ((x1 - x2) / 2*n) + (spam / k**3) If you are reading carefully, you may be curious why, in her temperature conversion program, Suzie Programmer chose to write 9.0/5.0 rather than 9/5. Both of these are legal expressions, but they give different results. This mystery will be discussed in Chapter 3. If you can’t stand the wait, try them out for yourself and see if you can figure out what’s going on. 2.4 Output Statements Now that you have the basic building blocks, identifier and expression, you are ready for a more complete description of various Python statements. You already know that you can display information on the screen using Python’s print statement. But what exactly can be printed? Python, like all programming languages, has a precise set of rulesfor the syntax (form) and semantics (meaning) of each statement. Computerscientists have developed sophisticated notations called meta-languages for describing programming languages. In this book we will rely on a simple template notation to illustrate the syntax of statements. Here are the possible forms of the print statement:
2.5.ASSIGNMENT STATEMENTS 17 print print <expr> print <expr>,<expr>,...,<expr> print <expr>,<expr>,...<expr>, In a nutshell,these templates show that a print statement consists of the keyword print followed by zero or more expressions,which are separated by commas.The angle bracket notation(=)is used to indicate "slots"that are filled in by other fragments of Python code.The name inside the brackets indicate what is missing;expr stands for an expression.The ellipses("..")indicate an indefinite series (of expressions, in this case).You don't actually type the dots.The fourth version shows that a print statement may be optionally ended with a comma.That is all there is to know about the syntax of print. As far as semantics,a print statement displays information in textual form.Any supplied expressions are evaluated left to right,and the resulting values are displayed on a single line of output in a left-to-right fashion.A single blank space character is placed between the displayed values. Normally,successive print statements will display on separate lines of the screen.A bare print(first version above)can be used to get a blank line of output.If a print statement ends with a comma (fourth version),a final space is appended to the line,but the output does not advance to the next line.Using this method,multiple print statements can be used to generate a single line of output. Putting it all together,this sequence of print statements print 3+4 print 3,4,3 +4 print print 3,4, print 3+4 print "The answer is",3 +4 produces this output 个 347 347 The answer is 7 That last print statement may be a bit confusing.According to the syntax templates above,print requires a sequence of expressions.That means "The answer is"must be an expression.In fact,it is an expression,but it doesn't produce a number.Instead,it produces another kind of data called a string. A sequence of characters enclosed in quotes is a string literal.Strings will be discussed in detail in a later chapter.For now,consider this a convenient way of labeling output. 2.5 Assignment Statements 2.5.1 Simple Assignment One of the most important kinds of statements in Python is the assignment statement.We've already seen a number of these in our previous examples.The basic assignment statement has this form: <variable><expr> Here variable is an identifier and expr is an expression.The semantics of the assignment is that the expression on the right side is evaluated to produce a value,which is then associated with the variable named on the left side Here are some of the assignments we've already seen. x=3.9*×*(1-x) fahrenheit =9.0 /5.0 celsius 32 x=5
2.5. ASSIGNMENT STATEMENTS 17 print print <expr> print <expr>, <expr>, ..., <expr> print <expr>, <expr>, ..., <expr>, In a nutshell, these templates show that a print statement consists of the keyword print followed by zero or more expressions, which are separated by commas. The angle bracket notation (✁) is used to indicate “slots” that are filled in by other fragments of Python code. The name inside the brackets indicate what is missing; expr stands for an expression. The ellipses (“...”) indicate an indefinite series (of expressions, in this case). You don’t actually type the dots. The fourth version shows that a print statement may be optionally ended with a comma. That is all there is to know about the syntax of print. As far as semantics, a print statement displays information in textual form. Any supplied expressions are evaluated left to right, and the resulting values are displayed on a single line of output in a left-to-right fashion. A single blank space character is placed between the displayed values. Normally, successive print statements will display on separate lines of the screen. A bare print (first version above) can be used to get a blank line of output. If a print statement ends with a comma (fourth version), a final space is appended to the line, but the output does not advance to the next line. Using this method, multiple print statements can be used to generate a single line of output. Putting it all together, this sequence of print statements print 3+4 print 3, 4, 3 + 4 print print 3, 4, print 3+4 print "The answer is", 3 + 4 produces this output 7 3 4 7 3 4 7 The answer is 7 That last print statement may be a bit confusing. According to the syntax templates above, print requires a sequence of expressions. That means "The answer is" must be an expression. In fact, it is an expression, but it doesn’t produce a number. Instead, it produces another kind of data called a string. A sequence of characters enclosed in quotes is a string literal. Strings will be discussed in detail in a later chapter. For now, consider this a convenient way of labeling output. 2.5 Assignment Statements 2.5.1 Simple Assignment One of the most important kinds of statements in Python is the assignment statement. We’ve already seen a number of these in our previous examples. The basic assignment statement has this form: <variable> = <expr> Here variable is an identifier and expr is an expression. The semantics of the assignment is that the expression on the right side is evaluated to produce a value, which is then associated with the variable named on the left side. Here are some of the assignments we’ve already seen. x = 3.9 * x * (1 - x) fahrenheit = 9.0 / 5.0 * celsius + 32 x = 5
18 CHAPTER 2.WRITING SIMPLE PROGRAMS A variable can be assigned many times.It always retains the value of the most recent assignment.Here is an interactive Python session that demonstrates the point: >>myVar =0 >>myvar 0 >>myVar 7 >>myvar 1 >>myVar myvar +1 >>myvar 8 The last assignment statement shows how the current value of a variable can be used to update its value.In this case I simply added one to the previous value.The chaos.py program from Chapter 1 did something similar,though a bit more complex.Remember,the values of variables can change:that's why they're called variables. 2.5.2 Assigning Input The purpose of an input statement is to get some information from the user of a program and store it into a variable.Some programming languages have a special statement to do this.In Python,input is accomplished using an assignment statement combined with a special expression called input.This template shows the standard form <variable>=input (<prompt>) Here prompt is an expression that serves to prompt the user for input,this is almost always a string literal (i.e.,some text inside of quotation marks). When Python encounters an input expression,it evaluates the prompt and displays the result of the prompt on the screen.Python then pauses and waits for the user to type an expression and press the <Enter>key.The expression typed by the user is then evaluated to produce the result of the input. This sounds complicated,but most uses of input are straightforward.In our example programs,input statements are used to get numbers from the user. x input("Please enter a number between 0 and 1:" celsius input("What is the Celsius temperature?" If you are reading programs carefully,you probably noticed the blank space inside the quotes at the end of these prompts.I usually put a space at the end of a prompt so that the input that the user types does not start right next to the prompt.Putting a space in makes the interaction easier to read and understand. Although these two examples specifically prompt the user to enter a number,a number is just a numeric literal-a simple Python expression.In fact,any valid expression would be just as acceptable.Consider the following interaction with the Python interpreter. >>ans input("Enter an expression:" Enter an expression:3 +4 *5 >>print ans 23 >>> Here,when prompted to enter an expression,the user typed"3+4 5."Python evaluated this expression and stored the value in the variable ans.When printed,we see that ans got the value 23 as expected. In a way,the input is like a delayed expression.The example interaction produced exactly the same result as if we had simply done ans =3 +4 5.The difference is that the expression was supplied at the time the statement was executed instead of being determined when the statement was written by the programmer.Thus,the user can supply formulas for a program to evaluate
18 CHAPTER 2. WRITING SIMPLE PROGRAMS A variable can be assigned many times. It always retains the value of the most recent assignment. Here is an interactive Python session that demonstrates the point: >>> myVar = 0 >>> myVar 0 >>> myVar = 7 >>> myVar 7 >>> myVar = myVar + 1 >>> myVar 8 The last assignment statement shows how the current value of a variable can be used to update its value. In this case I simply added one to the previous value. The chaos.py program from Chapter 1 did something similar, though a bit more complex. Remember, the values of variables can change; that’s why they’re called variables. 2.5.2 Assigning Input The purpose of an input statement is to get some information from the user of a program and store it into a variable. Some programming languages have a special statement to do this. In Python, input is accomplished using an assignment statement combined with a special expression called input. This template shows the standard form. <variable> = input(<prompt>) Here prompt is an expression that serves to prompt the user for input; this is almost always a string literal (i.e., some text inside of quotation marks). When Python encounters an input expression, it evaluates the prompt and displays the result of the prompt on the screen. Python then pauses and waits for the user to type an expression and press the Enter key. The expression typed by the user is then evaluated to produce the result of the input. This sounds complicated, but most uses of input are straightforward. In our example programs, input statements are used to get numbers from the user. x = input("Please enter a number between 0 and 1: ") celsius = input("What is the Celsius temperature? ") If you are reading programs carefully, you probably noticed the blank space inside the quotes at the end of these prompts. I usually put a space at the end of a prompt so that the input that the user types does not start right next to the prompt. Putting a space in makes the interaction easier to read and understand. Although these two examples specifically prompt the user to enter a number, a number is just a numeric literal—a simple Python expression. In fact, any valid expression would be just as acceptable. Consider the following interaction with the Python interpreter. >>> ans = input("Enter an expression: ") Enter an expression: 3 + 4 * 5 >>> print ans 23 >>> Here, when prompted to enter an expression, the user typed “3 + 4 * 5.” Python evaluated this expression and stored the value in the variable ans. When printed, we see that ans got the value 23 as expected. In a way, the input is like a delayed expression. The example interaction produced exactly the same result as if we had simply done ans = 3 + 4 * 5. The difference is that the expression was supplied at the time the statement was executed instead of being determined when the statement was written by the programmer. Thus, the user can supply formulas for a program to evaluate
2.5.ASSIGNMENT STATEMENTS 19 2.5.3 Simultaneous Assignment There is an alternative form of the assignment statement that allows us to calculate several values all at the same time.It looks like this: <var>,<var>,...,<var><expr>,<expr>,...,<expr> This is called simultaneous assignment.Semantically,this tells Python to evaluate all the expressions on the right-hand side and then assign these values to the corresponding variables named on the left-hand side. Here's an example. sum,diff x+y,x-y Here sum would get the sum of x and y and diff would get the difference This form of assignment seems strange at first,but it can prove remarkably useful.Here's an example. Suppose you have two variables x and y and you want to swap the values.That is,you want the value currently stored in x to be in y and the value that is currently in y to be stored in x.At first,you might think this could be done with two simple assignments. x=y y=x This doesn't work.We can trace the execution of these statements step-by-step to see why. Suppose x and y start with the values 2 and 4.Let's examine the logic of the program to see how the variables change.The following sequence uses comments to describe what happens to the variables as these two statements are executed. variables x y initial values 2 4 x=y #now 44 y=x final 44 See how the first statement clobbers the original value of x by assigning to it the value of y?When we then assign x to y in the second step,we just end up with two copies of the original y value. One way to make the swap work is to introduce an additional variable that temporarily remembers the original value of x. temp x x =y y=temp Let's walk-through this sequence to see how it works. variables x y temp initial values 2 4 no value yet temp x 242 x=y 44 3 y temp 422 As you can see from the final values ofx and y,the swap was successful in this case. This sort of three-way shuffle is common in other programming languages.In Python,the simultaneous assignment statement offers an elegant alternative.Here is a simpler Python equivalent: XI y =y x
2.5. ASSIGNMENT STATEMENTS 19 2.5.3 Simultaneous Assignment There is an alternative form of the assignment statement that allows us to calculate several values all at the same time. It looks like this: <var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr> This is called simultaneous assignment. Semantically, this tells Python to evaluate all the expressions on the right-hand side and then assign these values to the corresponding variables named on the left-hand side. Here’s an example. sum, diff = x+y, x-y Here sum would get the sum of x and y and diff would get the difference. This form of assignment seems strange at first, but it can prove remarkably useful. Here’s an example. Suppose you have two variables x and y and you want to swap the values. That is, you want the value currently stored in x to be in y and the value that is currently in y to be stored in x. At first, you might think this could be done with two simple assignments. x = y y = x This doesn’t work. We can trace the execution of these statements step-by-step to see why. Suppose x and y start with the values 2 and 4. Let’s examine the logic of the program to see how the variables change. The following sequence uses comments to describe what happens to the variables as these two statements are executed. # variables x y # initial values 2 4 x = y # now 4 4 y = x # final 4 4 See how the first statement clobbers the original value of x by assigning to it the value of y? When we then assign x to y in the second step, we just end up with two copies of the original y value. One way to make the swap work is to introduce an additional variable that temporarily remembers the original value of x. temp = x x = y y = temp Let’s walk-through this sequence to see how it works. # variables x y temp # initial values 2 4 no value yet temp = x # 2 4 2 x = y # 4 4 2 y = temp # 4 2 2 As you can see from the final values of x and y, the swap was successful in this case. This sort of three-way shuffle is common in other programming languages. In Python, the simultaneous assignment statement offers an elegant alternative. Here is a simpler Python equivalent: x, y = y, x