• Tidak ada hasil yang ditemukan

Chapter 2 Chapter 2

12.51 Assignment Statements

One of the most important kinds of statements in Python is the assignment state­

ment. We've already seen a number of these in our previous examples.

2.5. Assignment Statements

12.5.11 Simple Assignment

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 I 5 * celsius + 32 X = 5

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 1 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.

Sometimes it's helpful to think of a variable as a sort of named storage loca­

tion in computer memory, a box that we can put a value in. When the variable changes, the old value is erased and a new one written in. Figure 2.1 shows how we might picture the effect of x = x + 1 using this model. This is exactly the way assignment works in some computer languages. It's also a very sim­

ple way to view the effect of assignment, and you'll find pictures similar to this throughout the book.

37

Before

X 10 X = X + 1

After

X 11

Figure 2.1: Variable as box view of x = x + 1

Python assignment statements are actually slightly different from the ''vari­

able as a box" model. In Python, values may end up anywhere in memory, and variables are used to refer to them. Assigning a variable is like putting one of those little yellow sticky notes on the value and saying, "this is x." Figure 2.2

gives a more accurate picture of the effect of assignment in Python.

An

ar­

row is used to show which value a variable refers to. Notice that the old value doesn't get erased by the new one; the variable simply switches to refer to the new value. The effect is like moving the sticky note from one object to another.

This is the way assignment actually works in Python, so you'll see some of these sticky-note style pictures sprinkled throughout the book as well.

Before

X

IL..--

----+---�� 1 0

X = X + 1

./

After

X 10

11

Figure 2.2: Variable as sticky note (Python) view of x = x + 1

By the way, even though the assignment statement doesn't directly cause the old value of a variable to be erased and overwritten, you don't have to worry about computer memory getting filled up with the "discarded" values. When a value is no longer referred to by any variable, it is no longer useful. Python will automatically clear these values out of memory so that the space can be used for new values. This is like going through your closet and tossing out anything that

2.5. Assignment Statements

doesn't have a sticky note to label it. In fact, this process of automatic memory management is actually called garbage collection.

12.5.21 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 spe­

cial statement to do this. In Python, input is accomplished using an assignment statement combined with a built-in function called input. The exact form of an input statement depends on what type of data you are trying to get from the user. For textual input, the statement will look like this:

<variable> = input (<prompt>)

Here <prompt > is a string expression that is used to prompt the user for input;

the prompt is almost always a string literal (i.e., some text inside of quotation marks).

When Python encounters a call to input, it prints the prompt on the screen.

Python then pauses and waits for the user to type some text and press the

<Enter > key. Whatever the user types is then stored as a string. Consider this simple interaction:

>>> name = input ( 11Enter your name: 11) Enter your name: John Yaya

>>> name

'John Yaya'

Executing the input statement caused Python to print out the prompt "Enter your name:" and then the interpreter paused waiting for user input. In this example, I typed John Yaya. As a result, the string' John Yaya' is remembered in the variable name. Evaluating name gives back the string of characters that I typed.

When the user input is a number, we need a slightly more complicated form of input statement:

<variable> = eval (input (<prompt>) )

Here I've added another built-in Python function eval that is ''wrapped around"

the input function. As you might guess, eval is short for "evaluate." In this form, the text typed by the user is evaluated as an expression to produce the value that is stored into the variable. So, for example, the string 113211 becomes

39

the number 32. If you look back at the example programs so far, you'll see a couple of examples where we've gotten numbers from the user like this.

x = eval (input ("Please enter a number between 0 and 1: ") ) celsius = eval (input ("What is the Celsius temperature? ") )

The important thing to remember is that you need to eval the input when you want a number instead of some raw text (a string).

If you are reading the example programs carefully, you probably noticed the blank space inside the quotes at the end of all 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 our numeric examples specifically prompted the user to enter a number, what the user types in this case 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 = eval (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 (via eval) and assigned the value to the variable ans.

When printed, we see that ans got the value 23 as expected. In a sense, the input-eval combination is like a delayed expression. The example interaction produced exactly the same result as if we had simply written ans = 3 + 4 * 5.

The difference is that the expression was supplied by the user at the time the statement was executed instead of being typed by the programmer when the program was written.

Beware: the eval function is very powerful and also potentially dangerous.

As this example illustrates, when we evaluate user input, we are essentially allowing the user to enter a portion of our program. Python will dutifully eval­

uate whatever they type. Someone who knows Python could exploit this ability to enter malicious instructions. For example, the user could type an expression that captures private information or deletes files on the computer. In computer security, this is called a code injection attack, because an attacker is injecting malicious code into the running program.

2.5. Assignment Statements

As a beginning programmer writing programs for your own personal use, computer scecurity is not much of an issue; if you are sitting at the computer running a Python program, then you probably have full access to the system and can find much easier ways to, say, delete all your files. However, when the input to a program is coming from untrusted sources, say from users on the Internet, the use of eval could be disasterous. Fortunately, you will see some safer alternatives in the next chapter.

12.5.31 Simultaneous Assignment

There is an alternative form of the assignment statement that allows us to cal­

culate several values all at the same time. It looks like this:

<var1>, <var2>, . . . , <varn> = <expr1>, <expr2>, . . . , <exprn>

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 andy, 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 andy, 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 andy 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

41

# now y = X

# final

4 4 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 toy 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

Because the assignment is simultaneous, it avoids wiping out one of the original values.

Simultaneous assignment can also be used to get multiple numbers from the user in a single input. Consider this program for averaging exam scores:

# avg2. py

# A simple program to average two exam scores

# Illustrates use of multiple input

2.6. Definite Loops 43

def main () :

print ("This program computes the average of two exam scores . ")

score!, score2 = eval (input ("Enter two scores separated by a comma: ") ) average = (score! + score2) I 2

print ("The average of the scores is: ", average) main ()

The program prompts for two scores separated by a comma. Suppose the user types 86, 92. The effect of the input statement is then the same as if we had done this assignment:

score!, score2 = 86, 92

We have gotten a value for each of the variables in one fell swoop. This example used just two values, but it could be generalized to any number of inputs.

Of course, we could have just gotten the input from the user with separate input statements:

score! - eval (input ("Enter the first score: ") ) score2 - eval (input ("Enter the second score: ") )

In some ways this may be better, as the separate prompts are more informative for the user. In this example the decision as to which approach to take is largely a matter of taste. Sometimes getting multiple values in a single input provides a more intuitive user interface, so it's a nice technique to have in your toolkit. Just remember that the multiple values trick will not work for string (non-evaled) input; when the user types a comma it will be just another character in the input string. The comma only becomes a separator when the string is subsequently evaluated.