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

In this chapter you 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.

  • How to use lists or tuples with dictionaries cooperatively to explore the contents of a dictionary.

  • How to use exception handling 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.

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.

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.

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

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 operator. 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 previous rules — 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 it is not!")
...
>>> if 2 > 1:
...     print("Yes it is!")
...
Yes, it is!

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

Repetition

You have seen how many times every element in a sequence, or every element in a dictionary, needs to be examined and compared. Doing this manually is impossibly boring and error prone for a person, even a fast touch-typist. In addition, if you enter these things in manually, you'll be caught off guard when the inevitable typo happens, or when something that you're evaluating is changed elsewhere, and your manually entered code can't easily accommodate that change.

To perform repetitive tasks, Python offers two kinds of repetition operations. Both are similar — in fact, they're almost identical — but each one lets you think about what you're doing differently so each one should have its place in your skill set.

How to Do Something — Again and Again

The two operations that enable you to initiate and control repetitive tasks are the while and for operations. The while operation tests for one truth condition, so it will be referred to as while ... :. The for operation uses each value from within a list, so it will be referred to as for ... in ... :.

The while ... : operation will first check for its test condition (the ... between the while and the :) and if it's True, it will evaluate the statements in its indented block a first time. After it reaches the end of its indented block, which can include other indented blocks, it will once again evaluate its test condition to see whether it is still True. If it is, it will repeat its actions again; however, if it is False, Python leaves the indented section and continues to evaluate the rest of the program after the while ...: section. If names are used in the test condition, then between the first repetition and the next (and the next, and so on), the value referred to by the name could have changed and on and on until there is some reason to stop.

Stopping the Repetition

The common term infinite loop refers to a sequence of code that will repeat forever. A simple example just sets up a while ... : statement that tests against something that is always going to result in True. For instance, just using True will always work. You should not type in the following code, because it's the kind of thing that's better to see than to have to do yourself:

>>> while True:
...     print ("You're going to get bored with this quickly")
...
You're going to get bored with this quickly
You're going to get bored with this quickly
You're going to get bored with this quickly
You're going to get bored with this quickly
You're going to get bored with this quickly

The preceding code continues forever, or until you break out of it. Inconvenient as it seems at first glance to have something that repeats forever, sometimes you may want this — for instance, repeating code is useful in a program that waits for the user to type something in, and when the user is done, returns to waiting.

However, sometimes you will want to know that if certain conditions are met, such as the right time of day, when the water has run out, when there are no more eggs to be made into omelets, and so on, that the repetition can be broken out of even when there is no explicit test in the top of the while ... : or when the list that's being used in the for ... in ... : doesn't have an end.

Infinite loops can be exited by using the break statement. When you try this out, make sure your indentation matches what's on the page:

>>>age=0
>>> while True:
how_old=input("Enter your age: ")
if how_old=="No":
    print("Don't be ashamed of your age!")
    break
num=int(how_old)
age=age+num
print("Your age is :")
print(age)
print("That is old!")
...
Enter your age: 1
Your age is :
1
That is old!
Enter your age: 2
Your age is :
3
That is old!
Enter your age: −3
Your age is :
0
That is old!
Enter your age: 50
Your age is :
50
That is old!
Enter your age: No
Don't be ashamed of your age!
>>>

In the preceding program, While, as you may recall, is always equal to True; therefore, the statement while True will always loop if left to its own devices. To solve this, you prompt the user for some info; in this case, their age. So long as they enter in a number, the program will add it to their age, giving them a total age and making it appear that they are getting older (unless they are savvy and enter in a negative number, in which case they will get younger!). If they enter only numbers, the program will run forever. However, if they ever enter in the string, No, the program will print Don't be ashamed of your age! and break out of the loop.

Note the position of the print statement and the break; if you place the print after the break instead of before, it will execute every time the program loops, instead of just when you break out of the loop. So be careful where you place your statements!

If you use break, it will only take you out of the most recent loop — if you have a while ... : loop that contains a for ... in ... : loop indented within it, a break within the for ... in ... : will not break out of the while ... :.

Both while ... : and for ... in ... : loops can have an else: statement at the end of the loop, but it will be run only if the loop doesn't end due to a break statement. In this case, else: could be better named something like done or on_completion, but else: is a convenient name because you've already seen it, and it's not hard to remember.

Handling Errors

You have seen examples of how Python reports errors in Chapter 2 and Chapter 3. Those errors usually contain a lot of information pertaining to what failed and how:

>>> fridge_contents = {"egg":8, "mushroom":20, "pepper":3, "cheese":2,
"tomato":4, "milk":13}
>>> if fridge_contents["orange juice"] > 3:
...     print("Sure, let's have some juice!")
...
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    if fridge_contents["orange juice"] > 3:
KeyError: 'orange juice'

Oops. There is no orange juice in the fridge right now, but it would be nice to be able to learn this without having to crash out of the program.

You have already learned one way to find out about the keys that are present in a dictionary, by using the keys method of the dictionary and then searching through the list of keys to determine whether the key you want is present. However, there's no reason not to take a shortcut. The last line of the error shown in the preceding code is:

KeyError: 'orange juice'

This says that the error Python encountered was an error with the key in the fridge_contents dictionary. You can use the error that Python has told you about to brace the program against that particular class of error. You do this with the special word try: telling Python to prepare for an error.

Trying Things Out

A try: statement sets up a situation in which an except: statement can follow it. Each except: statement handles the error, which is formally named an exception that was just raised when Python evaluated the code within the try: statement instead of failing. To start with, use except: to handle one type of error — for instance, the KeyError that you get when trying to check the fridge.

You have only one line in which to handle the error, which may seem restrictive, but in Chapter 5 you learn how to write your own functions so you can handle errors with more flexibility.

>>> fridge_contents = {"egg":8, "mushroom":20, "pepper":3, "cheese":2,
"tomato":4, "milk":13}
>>> try:
...     if fridge_contents["orange juice"] > 3:
...         print("Sure, let's have some juice!")
... except KeyError:
...     print("Awww, there is no juice. Let's go shopping!")
...
Aww, there's no juice.  Lets go shopping

You may find that you need to print more information about the error itself, and this is the information that you have access to.

Summary

In this chapter, you learned about the methods for making decisions that Python offers. Any operation that results in True or False can be used by if ... : statements to determine whether a program will evaluate an indented block of code.

You have seen for the first time the important role that indentation plays in Python programs. Even in the interactive Python shell the number of spaces in the indentation matters.

You now have the knowledge to use sequence and dictionary elements in repetition loops. By using repetitions, you can perform operations on every element in a list and make decisions about the values of each list element.

The two types of repeating loops that Python offers you are the while ... : loop and the for ... in ... : loop. They perform similar jobs, continuing until a condition causes them to finish. The difference between the two lies in the conditions that will permit them to evaluate their indented block of code. The while ... : loop only tests for True or False in its test case, while the for ... in ... : loop will take a sequence you provide in the in ... : section, and each element from first to last in the sequence will be assigned to the value provided in the for ... section.

Both types of repeating loops can be exited before their test conditions are met by using the break operation. The break operation will cause the loop that is being evaluated to stop without further evaluations of any more code in the loop's code block. However, if a break operation is performed, the optional else: condition for a loop will not be run. In addition to break is the continue operation, which will skip the rest of the current loop but return to the top of the loop and evaluate the next test case.

You also learned about one other kind of decision making, which is handling the exceptions that Python uses to report errors. These exceptions are how any error is reported. If they are not accommodated, these errors will result in your program stopping at the point at which the error occurred. However, if you enclose code that may cause an error in a code block indented beneath a try: you can specify how to prevent the program from exiting, even going so far as handling the error and continuing with the program. The errors that you anticipate encountering will be specified in the except ... : clause, where the first value provided defines the type of the error (or types if a tuple of error types is provided); and, optionally, the word as followed by a name used to refer to data containing information about the error, can be provided.

The key things to take away from this chapter are:

  • You can test for equality using two equal signs (==). If the answer is True, True will be returned. If False, False will be returned. Double equals can also be used to determine if two variables hold the same data.

  • If you need to know if two values are not equal, you can use the not equal operator (!=). In this instance, True means that the values compared are not equal and False means that the compared values are equal.

  • To compare if a value is greater or less than another value, you can use the greater than (>) and less than (<) operators, respectively. If you need to know if a value is equal to or greater/lesser than, you would use the greater- than-or-equal-to operator (>=) or the less-than-or-equal-to operator (<=).

  • If you need a program to make a decision based on if a value is true or false, you can use the if statement, which simply states, if this is true, do that. To have your program do something if one value is true, and something else if it is not, you can use if...elif.

  • Sometimes you will need to loop through a certain action a number of times. Using the while loop, you can repeat or iterate the action for as long as the while condition equals true, or literally speaking, while this is true, do this.

  • If you need to loop through an action a set number of times, you can do so using the for loop, which uses a loop counter to tell how many times to repeat a given action.

  • A try: statement sets up a situation in which an except: statement can follow it. Each except: statement handles the error, which is formally named an exception that was just raised when Python evaluated the code within the try: statement instead of failing.

Exercises

Perform all of the following in the codeEditor Python shell:

  1. Using a series of if ... : statements, evaluate whether the numbers from 0 through 4 are True or False by creating five separate tests.

  2. Create a test using a single if ... : statement that will tell you whether a value is between 0 and 9 inclusively (that is, the number can be 0 or 9 as well as all of the numbers in between, not just 1-8) and print a message if it's a success. Test it.

  3. Using if ... :, elif,...: and else:, create a test for whether a value referred to by a name is in the first two elements of a sequence. Use the if ... : to test for the first element of the list; use elif ... : to test the second value referenced in the sequence; and use the else: clause to print a message indicating whether the element being searched for is not in the list.

  4. Create a dictionary containing foods in an imaginary refrigerator, using the name fridge. The name of the food will be the key, and the corresponding value of each food item should be a string that describes the food. Then create a name that refers to a string containing the name of a food. Call the name food_sought. Modify the test from Exercise 3 to be a simple if ... : test (no elif ... : or else: will be needed here) for each key and value in the refrigerator using a for ... in ... : loop to test every key contained in the fridge. If a match is found, print a message that contains the key and the value and then use break to leave the loop. Use an else ... : statement at the end of the for loop to print a message for cases in which the element wasn't found.

  5. Modify Exercise 3 to use a while ... : loop by creating a separate list called fridge_list that will contain the values given by fridge.keys. As well, use a variable named, current_key that will refer to the value of the current element in the loop that will be obtained by the method fridge_list.pop. Remember to place fridge_list.pop as the last line of the while ... : loop so that the repetition will end normally. Use the same else: statement at the end of the while loop as the one used at the end of Exercise 3.

  6. Query the fridge dictionary created in Exercise 3 for a key that is not present, and elicit an error. In cases like this, the KeyError can be used as a shortcut to determining whether or not the value you want is in the list. Modify the solution to Exercise 3 so that instead of using a for ... in ... : a try: block is used.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.36.146