Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Python (2005)

.pdf
Скачиваний:
158
Добавлен:
17.08.2013
Размер:
15.78 Mб
Скачать

Variables — Names for Values

>>>todays_temperatures = [23, 32, 33, 31]

>>>todays_temperatures.append(29)

>>>todays_temperatures

[23, 32, 33, 31, 29]

>>>morning = todays_temperatures.pop(0)

>>>print “This mornings temperature was %.02f” % morning This mornings temperature was 23.00

>>>late_morning = todays_temperatures.pop(0)

>>>print “Todays late morning temperature was %.02f” % late_morning Todays late morning temperature was 32.00

>>>noon = todays_temperatures.pop(0)

>>>print “Todays noon temperature was %.02f” % noon

Todays noon temperature was 33.00

>>> todays_temperatures [31, 29]

How It Works

When a value is popped, if the action is on the right-hand side of an equals sign, you can assign the element that was removed to a value on the left-hand side, or just use that value in cases where it would be appropriate. If you don’t assign the popped value or otherwise use it, it will be discarded from the list.

You can also avoid the use of an intermediate name, by just using pop to populate, say, a string format, because pop will return the specified element in the list, which can be used just as though you’d specified a number or a name that referenced a number:

>>>print “Afternoon temperature was %.02f” % todays_temperatures.pop(0) Afternoon temperature was 31.00

>>>todays_temperatures

[29]

If you don’t tell pop to use a specific element (0 in the examples) from the list it’s invoked from, it will remove the last element of the list, not the first as shown here.

Summar y

In this chapter, you learned how to manipulate many core types that Python offers. These types are tuples, lists, dictionaries, and three special types: None, True, and False. You’ve also learned a special way that strings can be treated like a sequence. The other sequence types are tuples and lists.

A tuple is a sequence of data that’s indexed in a fixed numeric order, starting at zero. The references in the tuple can’t be changed after the tuple is created. Nor can it have elements added or deleted. However, if a tuple contains a data type that has changeable elements, such as a list, the elements of that data type are not prevented from changing. Tuples are useful when the data in the sequence is better off not changing, such as when you want to explicitly prevent data from being accidentally changed.

A list is another type of sequence, which is similar to a tuple except that its elements can be modified. The length of the list can be modified to accommodate elements being added using the append method, and the length can be reduced by using the pop method. If you have a sequence whose data you want to append to a list, you can append it all at once with the extend method of a list.

41

TEAM LinG

Chapter 3

Dictionaries are yet another kind of indexed grouping of data. However, whereas lists and tuples are indexed by numbers, dictionaries are indexed by values that you choose. To explore the indexes, which are called keys, you can invoke the keys method. To explore the data that is referred to, called the values, you can use the values method. Both of these methods return lists.

Other data types are True, False, and None. True and False are a special way of looking at 1 and 0, but when you want to test whether something is true or false, explicitly using the names True and False is always the right thing to do. None is a special value that is built into Python that only equals itself, and it is what you receive from functions that otherwise would not return any value (such as True, False, a string, or other values).

Exercises

Perform all of the following in the codeEditor Python shell:

1.Create a list called dairy_section with four elements from the dairy section of a supermarket.

2.Print a string with the first and last elements of the dairy_section list.

3.Create a tuple called milk_expiration with three elements: the month, day, and year of the expiration date on the nearest carton of milk.

4.Print the values in the milk_expiration tuple in a string that reads “This milk carton will expire on 12/10/2005”.

5.Create an empty dictionary called milk_carton. Add the following key/value pairs. You can make up the values or use a real milk carton:

expiration_date — Set it to the milk_expiration tuple.

fl_oz — Set it to the size of the milk carton on which you are basing this.

Cost — Set this to the cost of the carton of milk.

brand_name — Set this to the name of the brand of milk you’re using.

6.Print out the values of all of the elements of the milk_carton using the values in the dictionary, and not, for instance, using the data in the milk_expiration tuple.

7.Show how to calculate the cost of six cartons of milk based on the cost of milk_carton.

8.Create a list called cheeses. List all of the cheeses you can think of. Append this list to the dairy_section list, and look at the contents of dairy_section. Then remove the list of cheeses from the array.

9.How do you count the number of cheeses in the cheese list?

10.Print out the first five letters of the name of your first cheese.

42

TEAM LinG

4

Making Decisions

So far, you have only seen how to manipulate data directly or through names to which the data is bound. Now that you have the basic understanding of how those data types can be manipulated manually, you can begin to exercise your knowledge of data types and use your data to make decisions.

In this chapter, you’ll learn about how Python makes decisions using True and False and how to make more complex decisions based on whether a condition is True or False.

You will learn how to create situations in which you can repeat the same actions using loops that give you the capability to automate stepping through lists, tuples, and dictionaries. You’ll also learn how to use lists or tuples with dictionaries cooperatively to explore the contents of a dictionary.

You will also be introduced to exception handling, which enables you to write your programs to cope with problematic situations that you can handle within the program.

Comparing Values — Are They the Same?

You saw True and False in Chapter 3, but you weren’t introduced to how they can be used. True and False are the results of comparing values, asking questions, and performing other actions. However, anything that can be given a value and a name can be compared with the set of comparison operations that return True and False.

Try It Out

Comparing Values for Sameness

Testing for equality is done with two equal signs — remember that the single equal sign will bind data to a name, which is different from what you want to do here, which is elicit a True or False:

>>>1 == 1

True

>>>1 == 2 False

TEAM LinG

Chapter 4

How It Works

When you use the equality comparison, Python will compare the values on both sides. If the numbers are different, False will be the result. If the numbers are the same, then True will be the result.

If you have different types of numbers, Python will still be able to compare them and give you the correct answer:

>>>1.23 == 1 False

>>>1.0 == 1

True

You can also use the double equals to test whether strings have the same contents, and you can even restrict this test to ranges within the strings (remember from the last chapter that slices create copies of the part of the strings they reference, so you’re really comparing two strings that represent just the range that a slice covers):

>>>a = “Mackintosh apples”

>>>b = “Black Berries”

>>>c = “Golden Delicious apples”

>>>a == b

False

>>>b == c False

>>>a[-len(“apples”):-1] == c[-len(“apples”):-1]

True

Sequences can be compared in Python with the double equals as well. Python considers two sequences to be equal when every element in the same position is the same in each list. Therefore, if you have three items each in two sequences and they contain the same data but in a different order, they are not equal:

>>>apples = [“Mackintosh”, “Golden Delicious”, “Fuji”, “Mitsu”]

>>>apple_trees = [“Golden Delicious”, “Fuji”, “Mitsu”, “Mackintosh”]

>>>apples == apple_trees

False

>>>apple_trees = [“Mackintosh”, “Golden Delicious”, “Fuji”, “Mitsu”]

>>>apples == apple_trees

True

In addition, dictionaries can be compared. Like lists, every key and value (paired, together) in one dictionary has to have a key and value in the other dictionary in which the key in the first is equal to the key in the second, and the value in the first is equal to the value in the second:

>>>tuesday_breakfast_sold = {“pancakes”:10, “french toast”: 4, “bagels”:32, “omelets”:12, “eggs and sausages”:13}

>>>wednesday_breakfast_sold = {“pancakes”:8, “french toast”: 5, “bagels”:22, “omelets”:16, “eggs and sausages”:22}

>>>tuesday_breakfast_sold == wednesday_breakfast_sold

False

>>>thursday_breakfast_sold = {“pancakes”:10, “french toast”: 4, “bagels”:32, “omelets”:12, “eggs and sausages”:13}

>>>tuesday_breakfast_sold == thursday_breakfast_sold

True

44

TEAM LinG

Making Decisions

Doing the Opposite — Not Equal

There is an opposite operation to the equality comparison. If you use the exclamation and equals together, you are asking Python for a comparison between any two values that are not equal (by the same set of rules of equality that you saw for the double equal signs) to result in a True value.

Try It Out

Comparing Values for Difference

>>>3 == 3

True

>>>3 != 3 False

>>>5 != 4

True

How It Works

Every pair of numbers that would generate a True result when they’re compared using the == will now generate a False, while any two numbers that would have generated a False when compared using == will now result in True.

These rules hold true for all of the more complex types, like sequences and dictionaries:

>>>tuesday_breakfast_sold != wednesday_breakfast_sold

True

>>>tuesday_breakfast_sold != thursday_breakfast_sold False

Like numbers, any situation that would be true with == will be False with != with these types.

Comparing Values — Which One Is More?

Equality isn’t the only way to find out what you want to know. Sometimes you will want to know whether a quantity of something is greater than that of another, or whether a value is less than some other value. Python has greater than and less than operations that can be invoked with the > and < characters, respectively. These are the same symbols you are familiar with from math books, and the question is always asking whether the value on the left is greater than (>) or less than (<) the value on the right.

Try It Out

Comparing Greater Than and Less Than

>>>5 < 3 False

>>>10 > 2

True

How It Works

The number on the left is compared to the number on the right. You can compare letters, too. There are a few conditions where this might not do what you expect, such as trying to compare letters to numbers. (The question just doesn’t come up in many cases, so what you expect and what Python expects is

45

TEAM LinG

Chapter 4

probably not the same.) The values of the letters in the alphabet run roughly this way: A capital “A” is the lowest letter. “B” is the next, followed by “C”, and so on until “Z.” This is followed by the lowercase letters, with “a” being the lowest lowercase letter and “z” the highest. However, “a” is higher than “Z”:

>>>“a” > “b” False

>>>“A” > “b” False

>>>“A” > “a” False

>>>“b” > “A”

True

>>>“Z” > “a” False

If you wanted to compare two strings that were longer than a single character, Python will look at each letter until it finds one that’s different. When that happens, the outcome will depend on that one difference. If the strings are completely different, the first letter will decide the outcome:

>>>“Zebra” > “aardvark” False

>>>“Zebra” > “Zebrb” False

>>>“Zebra” < “Zebrb”

True

You can avoid the problem of trying to compare two words that are similar but have differences in capitalization by using a special method of strings called lower, which acts on its string and return a new string with all lowercase letters. There is also a corresponding upper method. These are available for every string in Python:

>>>“Pumpkin” == “pumpkin” False

>>>“Pumpkin”.lower() == “pumpkin”.lower()

True

>>>“Pumpkin”.lower()

‘pumpkin’

>>>“Pumpkin”.upper() == “pumpkin”.upper()

True

>>>“pumpkin”.upper()

‘PUMPKIN’

When you have a string referenced by a name, you can still access all of the methods that strings normally have:

>>>gourd = “Calabash”

>>>gourd

‘Calabash’

>>>gourd.lower()

‘calabash’

>>>gourd.upper()

‘CALABASH’

46

TEAM LinG

Making Decisions

More Than or Equal, Less Than or Equal

There is a useful variation on greater than and less than. It’s common to think of things in terms of greater than or equal to or less than or equal to. You can use a simple shorthand to do that: Join the two symbols in a way that makes sense when you look at it:

>>>1 > 1 False

>>>1 >= 2 False

>>>10 < 10 False

>>>10 <= 10

True

Reversing True and False

When you are creating situations where you’re comparing their outcomes, sometimes you want to know whether something is true, and sometimes you want to know whether something is not true. Sensibly enough, Python has an operation to create the opposite situation — the word not provides the opposite of the truth value that follows it.

Try It Out

Reversing the Outcome of a Test

>>>not True False

>>>not 5 False

>>>not 0

True

How It Works

The not operation applies to any test that results in a True or False. However, remember from Chapter 3 that anything that’s not zero will be seen as True, so you can use not in many situations where you wouldn’t expect it or where it doesn’t necessarily make sense:

>>>not 5 > 2 False

>>>not “A” < 3

True

>>>not “A” < “z” False

47

TEAM LinG

Chapter 4

Looking for the Results of More

Than One Comparison

You can also combine the results of more than one operation, which enables your programs to make more complex decisions by evaluating the truth values of more than one operation.

One kind of combination is the and operation, which says “if the operation, value, or object on my left evaluates to being True, move to my right and evaluate that. If it doesn’t evaluate to True, just stop and say False — don’t do any more.”

>>>True and True

True

>>>False and True False

>>>True and False False

>>>False and False False

The other kind of combining operation is the or compound. Using the or tells Python to evaluate the expression on the left, and if it is False, Python will evaluate the expression on the right. If it is True, Python will stop evaluation of any more expressions:

>>>True or True

True

>>>True or False

True

>>>False or True

True

>>>False or False False

You may also want to place sequences of these together based on actions you want to happen. In these cases, evaluation starts with the leftmost and or or and continues following the rules above — in other words, until a False value is evaluated for and, or until a True value is evaluated for or.

How to Get Decisions Made

Python has a very simple way of letting you make decisions. The reserved word for decision making is if, and it is followed by a test for the truth of a condition, and the test is ended with a colon, so you’ll see it referred to here as if ... :. It can be used with anything that evaluates to True or False to say “if something is true, do what follows”:

>>> if 1 > 2:

... print ‘No, its not’

...

>>> if 2 > 1:

... print ‘Yes, it is’

...

Yes, it is

48

TEAM LinG

Making Decisions

You have just seen one of the most distinctive visual aspects of Python and the one that most people remark on when they encounter Python.

When you see the colon in Python programs, it’s an indication that Python is entering a part of its program that is partially isolated from the rest of the program. At this point, indentation becomes important. The indentation is how Python knows that a particular block of code is separate from the code around it. The number of spaces used is important, and a Python-oriented programming editor will always carefully help you maintain the proper indentation for the code that is being written. The number of spaces is relevant, so it is important to use the editor to determine your indentation and not change the number of spaces manually.

You will see more keywords paired with the colon; and in all cases, you need to pay attention to the indentation. Python will warn you with an error if your program has changes in indentation that it doesn’t understand.

Only when the statements to be evaluated between the if and the colon evaluate to True will the indented statements below be visited by Python to be evaluated. The indentation indicates that the code that follows it is a part of the program but is only executed only if the right conditions occur. For the

if ... : statement, the proper condition is when the comparison being made evaluates to True.

You can place if ... : statements within the indentation of other if ... : statements to perform more complex decisions than what can be achieved with and and or because using if ... : enables you to perform any series of statements that you may need before evaluating the indented if ... : statement.

Try It Out Placing Tests within Tests

Try the following example, where one if ...: appears within another:

>>>omelet_ingredients = {“egg”:2, “mushroom”:5, “pepper”:1, “cheese”:1, “milk”:1}

>>>fridge_contents = {“egg”:10, “mushroom”:20, “pepper”:3, “cheese”:2, “tomato”:4, “milk”:15}

>>>have_ingredients = [True]

>>>if fridge_contents[“egg”] > omelet_ingredients[“egg”]:

... have_ingredients[0] = False

... have_ingredients.append(“egg”)

...

>>> if fridge_contents[“mushroom”] > omelet_ingredients[“mushroom”]:

...

if have_ingredients[0] == True:

...

have_ingredients[0] = False

...

have_ingredients.append(“mushroom”)

...

 

How It Works

After a condition is tested with an if ...: and there is an additional level of indentation, Python will continue to evaluate the rest of the code that you’ve placed in the indentation. If the first if ...: isn’t true, then none of the code below it will be evaluated — it would be skipped entirely.

However, if the first if ...: statement is true, the second one at the same level will be evaluated. The outcome of a comparison only determines whether the indented code beneath it will be run. Code at the

49

TEAM LinG

Chapter 4

same level, or above, won’t be stopped without something special happening, like an error or another condition that would prevent the program from continuing to run.

To complete the example, you could enter the rest of this (if you want to make a computer representation of an omelet):

>>> if fridge_contents[“pepper”] > omelet_ingredients[“pepper”]:

...

if have_ingredients[0] == True:

...

have_ingredients[0] = False

...

have_ingredients.append(“pepper”)

...

 

>>> if fridge_contents[“cheese”] > omelet_ingredients[“cheese”]:

...

if have_ingredients[0] == True:

...

have_ingredients[0] = False

...

have_ingredients.append(“cheese”)

...

>>> if fridge_contents[“milk”] > omelet_ingredients[“milk”]:

...

if have_ingredients[0] == True:

...

have_ingredients[0] = False

...

have_ingredients.append(“milk”)

...

 

>>> if have_ingredients[0] == True :

...

print “I can make an omelet now”

...

I can make an omelet now

You can create a chain of tests beginning with if ... : using elif ... :. elif ... : enables a variety of conditions to be tested for but only if a prior condition wasn’t met. If you use a series of if ... : statements they will all be executed. If you use an if ... : followed by an elif ... :, the elif ... : will be evaluated only if the if ... : results in a False value:

>>>milk_price = 1.50

>>>if milk_price < 1.25:

...

print “Buy two cartons of milk, they’re on sale”

... elif milk_price < 2.00:

...

print “Buy one carton of milk, prices are normal”

... elif milk_price > 2.00:

...

print “Go somewhere else! Milk costs too much here”

...

Buy one carton of milk, prices are normal

There is also a fall-through statement that you can insert to handle those cases where none of the prior tests resulted in a True value: the else: statement. If none of the if ... : or elif ... : statements have test conditions that evaluate to True, the else: clause is invoked:

>>>OJ_price = 2.50

>>>if OJ_price < 1.25:

...

print “Get one, I’m thirsty”

... elif OJ_price <= 2.00:

...

print “Ummm... sure, but I’ll drink it slowly”

... else:

...

print “I don’t have enough money. Never mind”

...

I don’t have enough money. Never mind

50

TEAM LinG