Appendix D Answers to Checkpoints 599 2.16 0 2.17 last_name = input(\"Enter the customer's last name: ”) 2.18 sales = float(input('Enter the sales for the week: ')) 2.19 Here is the completed table: Expression Value 6+3*5 21 12 / 2 − 4 2 9 + 14 * 2 − 6 31 (6 + 2) * 3 24 14 / (11 − 4) 2 9 + 12 * (8 − 3) 69 2.20 4 2.21 1 Chapter 3 3.1 A logical design that controls the order in which a set of statements execute 3.2 It is a program structure that can execute a set of statements only under certain circumstances. 3.3 A decision structure that provides a single alternative path of execution. If the condition that is being tested is true, the program takes the alternative path. 3.4 An expression that can be evaluated as either true or false 3.5 You can determine whether one value is greater than, less than, greater than or equal to, less than or equal to, equal to, or not equal to another value. 3.6 if y == 20: x = 0 3.7 if sales >= 10000: commissionRate = 0.2 3.8 A dual alternative decision structure has two possible paths of execution; one path is taken if a condition is true, and the other path is taken if the condition is false. 3.9 if-else 3.10 When the condition is false 3.11 z is not less than a. 3.12 Boston New York
600 Appendix D Answers to Checkpoints 3.13 if number == 1: print('One') elif number == 2: print('Two') elif number == 3: print('Three') else: print('Unknown') 3.14 It is an expression that is created by using a logical operator to combine two Boolean subexpressions. 3.15 F T F F T T T F F T 3.16 T F T T T 3.17 The and operator: If the expression on the left side of the and operator is false, the expression on the right side will not be checked. The or operator: If the expression on the left side of the or operator is true, the expression on the right side will not be checked. 3.18 if speed >= 0 and speed <= 200: print('The number is valid') 3.19 if speed < 0 or speed > 200: print('The number is not valid') 3.20 True or False 3.21 A variable that signals when some condition exists in the program Chapter 4 4.1 A structure that causes a section of code to repeat 4.2 A loop that uses a true/false condition to control the number of times that it repeats 4.3 A loop that repeats a specific number of times 4.4 An execution of the statements in the body of the loop
Appendix D Answers to Checkpoints 601 4.5 Before 4.6 None. The condition count < 0 will be false to begin with. 4.7 A loop that has no way of stopping and repeats until the program is interrupted. 4.8 for x in range(6): print('I love to program!') 4.9 0 1 2 3 4 5 4.10 2 3 4 5 4.11 0 100 200 300 400 500 4.12 10 9 8 7 6 4.13 A variable that is used to accumulate the total of a series of numbers 4.14 Yes, it should be initialized with the value 0. This is because values are added to the accumulator by a loop. If the accumulator does not start at the value 0, it will not contain the correct total of the numbers that were added to it when the loop ends. 4.15 15 4.16 15 5 4.17 a) quantity += 1 b) days_left −= 5 c) price *= 10 d) price /= 2 4.18 A sentinel is a special value that marks the end of a list of items. 4.19 A sentinel value must be unique enough that it will not be mistaken as a regular value in the list.
602 Appendix D Answers to Checkpoints 4.20 It means that if bad data (garbage) is provided as input to a program, the program will produce bad data (garbage) as output. 4.21 When input is given to a program, it should be inspected before it is processed. If the input is invalid, then it should be discarded and the user should be prompted to enter the correct data. 4.22 The input is read, and then a pretest loop is executed. If the input data is invalid, the body of the loop executes. In the body of the loop, an error message is displayed so the user will know that the input was invalid, and then the input read again. The loop repeats as long as the input is invalid. 4.23 It is the input operation that takes place just before an input validation loop. The purpose of the priming read is to get the first input value. 4.24 None Chapter 5 5.1 A function is a group of statements that exist within a program for the pur- pose of performing a specific task. 5.2 A large task is divided into several smaller tasks that are easily performed. 5.3 If a specific operation is performed in several places in a program, a function can be written once to perform that operation and then be executed any time it is needed. 5.4 Functions can be written for the common tasks that are needed by the different programs. Those functions can then be incorporated into each program that needs them. 5.5 When a program is developed as a set of functions in which each performs an individual task, then different programmers can be assigned the job of writing different functions. 5.6 A function definition has two parts: a header and a block. The header indicates the starting point of the function, and the block is a list of statements that belong to the function. 5.7 To call a function means to execute the function. 5.8 When the end of the function is reached, the computer returns back to the part of the program that called the function, and the program resumes execution at that point. 5.9 Because the Python interpreter uses the indentation to determine where a block begins and ends 5.10 A local variable is a variable that is declared inside a function. It belongs to the function in which it is declared, and only statements in the same function can access it. 5.11 The part of a program in which a variable may be accessed
Appendix D Answers to Checkpoints 603 5.12 Yes, it is permissible. 5.13 Arguments 5.14 Parameters 5.15 A parameter variable’s scope is the entire function in which the parameter is declared. 5.16 No, it does not. 5.17 a. passes by keyword argument b. passes by position 5.18 The entire program 5.19 Here are three: • Global variables make debugging difficult. Any statement in a program can change the value of a global variable. If you find that the wrong value is being stored in a global variable, you have to track down every statement that accesses it to determine where the bad value is coming from. In a program with thousands of lines of code, this can be difficult. • Functions that use global variables are usually dependent on those variables. If you want to use such a function in a different program, you will most likely have to redesign it so it does not rely on the global variable. • G lobal variables make a program hard to understand. A global variable can be modified by any statement in the program. If you are to understand any part of the program that uses a global variable, you have to be aware of all the other parts of the program that access the global variable. 5.20 A global constant is a name that is available to every function in the program. It is permissible to use global constants. Because their value cannot be changed during the program’s execution, you do not have to worry about its value being altered. 5.21 The difference is that a value returning function returns a value back to the statement that called it. A simple function does not return a value. 5.22 A prewritten function that performs some commonly needed task 5.23 The term “black box” is used to describe any mechanism that accepts input, performs some operation (that cannot be seen) using the input, and produces output. 5.24 It assigns a random integer in the range of 1 through 100 to the variable x. 5.25 It prints a random integer in the range of 1 through 20. 5.26 It prints a random integer in the range of 10 through 19. 5.27 It prints a random floating-point number in the range of 0.0 up to, but not including, 1.0. 5.28 It prints a random floating-point number in the range of 0.1 through 0.5. 5.29 It uses the system time, retrieved from the computer’s internal clock.
604 Appendix D Answers to Checkpoints 5.30 If the same seed value were always used, the random number functions would always generate the same series of pseudorandom numbers. 5.31 It returns a value back to the part of the program that called it. 5.32 a) do_something b) It returns a value that is twice the argument passed to it. c) 20 5.33 A function that returns either True or False 5.34 import math 5.35 square_root = math.sqrt(100) 5.36 angle = math.radians(45) Chapter 6 6.1 A file to which a program writes data. It is called an output file because the program sends output to it. 6.2 A file from which a program reads data. It is called an input file because the program receives input from it. 6.3 (1) Open the file. (2) Process the file. (3) Close the file. 6.4 Text and binary. A text file contains data that has been encoded as text using a scheme such as ASCII. Even if the file contains numbers, those numbers are stored in the file as a series of characters. As a result, the file may be opened and viewed in a text editor such as Notepad. A binary file contains data that has not been converted to text. As a consequence, you cannot view the con- tents of a binary file with a text editor. 6.5 Sequential and direct access. When you work with a sequential access file, you access data from the beginning of the file to the end of the file. When you work with a direct access file, you can jump directly to any piece of data in the file without reading the data that comes before it. 6.6 The file’s name on the disk and the name of a variable that references a file object. 6.7 The file’s contents are erased. 6.8 Opening a file creates a connection between the file and the program. It also creates an association between the file and a file object. 6.9 Closing a file disconnects the program from the file. 6.10 A file’s read position marks the location of the next item that will be read from the file. When an input file is opened, its read position is initially set to the first item in the file.
Appendix D Answers to Checkpoints 605 6.11 You open the file in append mode. When you write data to a file in append mode, the data is written to the end of the file’s existing contents. 6.12 outfile = open('numbers.txt', 'w') for num in range(1, 11): outfile.write(str(num) + '\\n') outfile.close() 6.13 The readline method returns an empty string ('') when it has attempted to read beyond the end of a file. 6.14 infile = open('numbers.txt', 'r') line = infile.readline() while line != '': print(line) line = infile.readline() infile.close() 6.15 infile = open('data.txt', 'r') for line in infile: print(line) infile.close() 6.16 A record is a complete set of data that describes one item, and a field is a single piece of data within a record. 6.17 You copy all the original file’s records to the temporary file, but when you get to the record that is to be modified, you do not write its old contents to the temporary file. Instead, you write its new, modified values to the temporary file. Then, you finish copying any remaining records from the original file to the temporary file. 6.18 You copy all the original file’s records to the temporary file, except for the record that is to be deleted. The temporary file then takes the place of the original file. You delete the original file and rename the temporary file, giving it the name that the original file had on the computer’s disk. 6.19 An exception is an error that occurs while a program is running. In most cases, an exception causes a program to abruptly halt. 6.20 The program halts. 6.21 IOError 6.22 ValueError Chapter 7 7.1 [1, 2, 99, 4, 5] 7.2 [0, 1, 2] 7.3 [10, 10, 10, 10, 10]
606 Appendix D Answers to Checkpoints 7.4 1 3 5 7 9 7.5 4 7.6 Use the built-in len function. 7.7 [1, 2, 3] [10, 20, 30] [1, 2, 3, 10, 20, 30] 7.8 [1, 2, 3] [10, 20, 30, 1, 2, 3] 7.9 [2, 3] 7.10 [2, 3] 7.11 [1] 7.12 [1, 2, 3, 4, 5] 7.13 [3, 4, 5] 7.14 Jasmine's family: ['Jim', 'Jill', 'John', 'Jasmine'] 7.15 The remove method searches for and removes an element containing a specific value. The del statement removes an element at a specific index. 7.16 You can use the built-in min and max functions. 7.17 You would use statement b, names.append('Wendy'). This is because element 0 does not exist. If you try to use statement a, an error will occur. 7.18 a) The index method searches for an item in the list and returns the index of the first element containing that item. b) The insert method inserts an item into the list at a specified index. c) The sort method sorts the items in the list to appear in ascending order. d) The reverse method reverses the order of the items in the list. 7.19 The list contains 4 rows and 2 columns. 7.20 mylist = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 7.21 for r in range(4): for c in range(2): print(numbers[r][c])
Appendix D Answers to Checkpoints 607 7.22 The primary difference between tuples and lists is that tuples are immutable. That means that once a tuple is created, it cannot be changed. 7.23 Here are three reasons: • Processing a tuple is faster than processing a list, so tuples are good choices when you are processing lots of data and that data will not be modified. • Tuples are safe. Because you are not allowed to change the contents of a tuple, you can store data in one and rest assured that it will not be modi- fied (accidentally or otherwise) by any code in your program. • There are certain operations in Python that require the use of a tuple. 7.24 my_tuple = tuple(my_list) 7.25 my_list = list(my_tuple) Chapter 8 8.1 for letter in name: print(letter) 8.2 0 8.3 9 8.4 An IndexError exception will occur if you try to use an index that is out of range for a particular string. 8.5 Use the built-in len function. 8.6 The second statement attempts to assign a value to an individual character in the string. Strings are immutable, however, so the expression animal[0] cannot appear on the left side of an assignment operator. 8.7 cde 8.8 defg 8.9 abc 8.10 abcdefg 8.11 if 'd' in mystring: print('Yes, it is there.') 8.12 little = big.upper() 8.13 if ch.isdigit(): print('Digit') else: print('No digit') 8.14 a A
608 Appendix D Answers to Checkpoints 8.15 again = input('Do you want to repeat ' + \\ 'the program or quit? (R/Q) ') while again.upper() != 'R' and again.upper() != 'Q': again = input('Do you want to repeat the ' + 'program or quit? (R/Q) ') 8.16 $ 8.17 for letter in mystring: if letter.isupper(): count += 1 8.18 my_list = days.split() 8.19 my_list = values.split('$') Chapter 9 9.1 Key and value 9.2 The key 9.3 The string 'start' is the key, and the integer 1472 is the value. 9.4 It stores the key-value pair 'id' : 54321 in the employee dictionary. 9.5 ccc 9.6 You can use the in operator to test for a specific key. 9.7 It deletes the element that has the key 654. 9.8 3 9.9 1 2 3 9.10 The pop method accepts a key as an argument, returns the value that is associated with that key, and removes that key-value pair from the dictionary. The popitem method returns a randomly selected key-value pair, as a tuple, and removes that key-value pair from the dictionary. 9.11 It returns all a dictionary’s keys and their associated values as a sequence of tuples. 9.12 It returns all the keys in a dictionary as a sequence of tuples. 9.13 It returns all the values in the dictionary as a sequence of tuples. 9.14 Unordered 9.15 No 9.16 You call the built-in set function. 9.17 The set will contain these elements (in no particular order): 'J', 'u', 'p', 'i', 't', 'e', and 'r'.
Appendix D Answers to Checkpoints 609 9.18 The set will contain one element: 25. 9.19 The set will contain these elements (in no particular order): 'w', ' ', 'x', 'y', and 'z'. 9.20 The set will contain these elements (in no particular order): 1, 2, 3, and 4. 9.21 The set will contain these elements (in no particular order): 'www', 'xxx', 'yyy', and 'zzz'. 9.22 You pass the set as an argument to the len function. 9.23 The set will contain these elements (in no particular order): 10, 9, 8, 1, 2, and 3. 9.24 The set will contain these elements (in no particular order): 10, 9, 8, 'a', 'b', and 'c'. 9.25 If the specified element to delete is not in the set, the remove method raises a KeyError exception, but the discard method does not raise an exception. 9.26 You can use the in operator to test for the element. 9.27 {10, 20, 30, 100, 200, 300} 9.28 {3, 4} 9.29 {1, 2} 9.30 {5, 6} 9.31 {'a', 'd'} 9.32 set2 is a subset of set1, and set1 is a superset of set2. 9.33 The process of converting the object to a stream of bytes that can be saved to a file for later retrieval. 9.34 'wb' 9.35 'rb' 9.36 The pickle module 9.37 pickle.dump 9.38 pickle.load Chapter 10 10.1 An object is a software entity that contains both data and procedures. 10.2 Encapsulation is the combining of data and code into a single object. 10.3 When an object’s internal data is hidden from outside code and access to that data is restricted to the object’s methods, the data is protected from accidental corruption. In addition, the programming code outside the object does not need to know about the format or internal structure of the object’s data.
610 Appendix D Answers to Checkpoints 10.4 Public methods can be accessed by entities outside the object. Private methods cannot be accessed by entities outside the object. They are designed to be accessed internally. 10.5 The metaphor of a blueprint represents a class. 10.6 Objects are the cookies. 10.7 Its purpose is to initialize an object’s data attributes. It executes immediately after the object is created. 10.8 When a method executes, it must have a way of knowing which object’s data attributes it is supposed to operate on. That’s where the self parameter comes in. When a method is called, Python automatically makes its self parameter reference the specific object that the method is supposed to operate on. 10.9 By starting the attribute’s name with two underscores 10.10 It returns a string representation of the object. 10.11 By passing the object to the built-in str method 10.12 An attribute that belongs to a specific instance of a class 10.13 10 10.14 A method that returns a value from a class’s attribute but does not change it is known as an accessor method. A method that stores a value in a data attribute or changes the value of a data attribute in some other way is known as a mutator method. 10.15 The top section is where you write the name of the class. The middle section holds a list of the class’s fields. The bottom section holds a list of the class’s methods. 10.16 A written description of the real-world objects, parties, and major events related to the problem 10.17 If you adequately understand the nature of the problem you are trying to solve, you can write a description of the problem domain yourself. If you do not thoroughly understand the nature of the problem, you should have an expert write the description for you. 10.18 First, identify the nouns, pronouns, and pronoun phrases in the problem domain description. Then, refine the list to eliminate duplicates, items that you do not need to be concerned with in the problem, items that represent objects instead of classes, and items that represent simple values that can be stored in variables. 10.19 The things that the class is responsible for knowing and the actions that the class is responsible for doing 10.20 In the context of this problem, what must the class know? What must the class do? 10.21 No, not always
Appendix D Answers to Checkpoints 611 Chapter 11 11.1 A superclass is a general class, and a subclass is a specialized class. 11.2 When one object is a specialized version of another object, there is an “is a” relationship between them. The specialized object “is a” version of the general object. 11.3 It inherits all the superclass’s attributes. 11.4 Bird is the superclass, and Canary is the subclass. 11.5 I’m a vegetable. I’m a potato. Chapter 12 12.1 A recursive algorithm requires multiple method calls. Each method call requires several actions to be performed by the JVM. These actions include allocating memory for parameters and local variables and storing the address of the program location where control returns after the method terminates. All these actions are known as overhead. In an iterative algorithm, which uses a loop, such overhead is unnecessary. 12.2 A case in which the problem can be solved without recursion 12.3 Cases in which the problem is solved using recursion 12.4 When it reaches the base case 12.5 In direct recursion, a recursive method calls itself. In indirect recursion, method A calls method B, which in turn calls method A. Chapter 13 13.1 The part of a computer and its operating system with which the user interacts 13.2 A command line interface typically displays a prompt, and the user types a command, which is then executed. 13.3 The program 13.4 A program that responds to events that take place, such as the user clicking a button 13.5 a) Label—An area that displays one line of text or an image b) Entry—An area in which the user may type a single line of input from the keyboard c) Button—A button that can cause an action to occur when it is clicked d) Frame—A container that can hold other widgets 13.6 You create an instance of the tkinter module’s Tk class. 13.7 This function runs like an infinite loop until you close the main window.
612 Appendix D Answers to Checkpoints 13.8 The pack method arranges a widget in its proper position, and it makes the widget visible when the main window is displayed. 13.9 One will be stacked on top of the other. 13.10 side=–left— 13.11 You use an Entry widget’s get method to retrieve the data that the user has typed into the widget. 13.12 It is a string. 13.13 tkinter 13.14 Any value that is stored in the StringVar object will automatically be displayed in the Label widget. 13.15 You would use radio buttons. 13.16 You would use check buttons. 13.17 When you create a group of Radiobuttons, you associate them all with the same IntVar object. You also assign a unique integer value to each Radiobutton widget. When one of the Radiobutton widgets is selected, it stores its unique integer value in the IntVar object. 13.18 You associate a different IntVar object with each Checkbutton. When a Checkbutton is selected, its associated IntVar object will hold the value 1. When a Checkbutton is deselected, its associated IntVar object will hold the value 0.
Index Symbols in subset determination, 418 != operator relationship testing, 103 = (assignment) operator, 103 defined, 104 == operator example use, 104, 106 assignment operator versus, 104 \" (double-quote marks), 56 defined, 102 \"\"\" or ''' (triple quotes), 56 in string comparisons, 112 # character, 57 use example, 106 % (remainder) operator > operator defined, 72, 78 defined, 102 function of, 233 in string comparisons, 114 %= operator, 161 use example, 102, 103–104 & operator, for intersection of sets, 416 >= operator ' (single-quote marks), 55–56 defined, 102 * operator in superset determination, 418 multiplication, 72 relationship testing, 103 repetition, 311 >>> prompt, 39, 40 ** (exponent) operator, 72, 76–78 ^ operator, 417 *= operator, 161 _ _init_ _ method, 447, 481, 487, 489, 509 + operator {}(curly braces), 388 defined, 72 displaying multiple items with, 86 A in list concatenation, 315 Accessor methods, 463 += operator acos (x) function, 237 defined, 161 Actions in list concatenation, 316 in string concatenation, 363 conditionally executed, 100 - (subtraction) operator, 72 in decision structures, 101 _ _str_ _ method, 455–458 Ada programming language, 35 - = operator, 161 Addition (+) operator / (division) operator, 72, 74 defined, 72 // (integer division) operator, 72, 74 displaying multiple items with, 86 /= operator, 161 precedence, 75 = operator add method, 412 defined, 102 Algebraic expressions, 79–80 613
614 Index Base classes, 500 BASIC, 35 Algorithms Binary files, 255 defined, 51 Binary numbering system, 27–28 example, 51 Bits, 29 recursive, 528, 529, 532–539 defined, 26 and operator patterns, 27, 28 defined, 124 Black boxes, library functions as, 214 false, 126 Blank lines, in blocks, 191 short-circuit evaluation, 125 Blocks truth table, 124 blank lines, 191 defined, 187 Appending data, 266 indentation, 190–191 append method nested, 118–119 statement format, 187 defined, 321–322 bool data type, 129 use example, 322–323 Boolean expressions Append mode, 266 defined, 101–102 Application software, 25 if statement testing, 101 Arguments with input validation loops, 165 defined, 199 with logical operators, 123 keyword, 207–209 with relational operators, 101–102 passing objects as, 466–467 Boolean functions passing to functions, 199–209 defined, 233 positional, 209 in validation code, 234 as step values, 151 Boolean values, returning, 233–234 Arrays, 311 Boolean variables, 129–130 ASCII Buffers, 259 character set, 29, 595 Buttons defined, 29 check, 574–576 in string comparisons, 112–114 Convert, 560, 562 asin () function, 237 OK, 556, 558, 571, 573 Assemblers, 33–34 Quit, 558–559, 560 Assembly language, 33–34 radio, 570–573 Assignment operators Button widget augmented, 161–162 defined, 548 == operator versus, 103 use example, 556–559 Assignment statements Bytes creating variables with, 58–61 in data storage, 26 example, 58 defined, 25 format, 59 for large numbers, 28 multiple assignment, 399 atan () function, 237 C Attributes. See Data attributes Calculations Augmented assignment operators, 161–162 Automobile class, 501–506 average, 76–77 Averages math expressions, 71 calculating, 76–77 math operators, 71, 72 list value, 332–333 percentage, 73–74 performing, 71–83 B BankAccount class example, 453–458 Base case, 529, 532, 534, 538
Index 615 Callback functions organization, 451 defined, 556 Classes. See also Instances as event handlers, 556 Radiobuttons with, 573 Automobile, 501–506 BankAccount, 453–458 Calling functions. See also Functions base, 500 defined, 54, 186 Car, 488–489, 503–505 examples of, 187 Cat, 516 general format, 54 CD, 511 illustrated, 188 CellPhone, 461–463 Checkbutton, 574–576 CamelCase, 62 Coin, 443–449 Canvas widget, 548 concept of, 441 Car class, 488–489, 503–505 Contact, 470–480 Case-sensitive comparisons, 373 cookie cutter metaphor, 442 Cat class, 516 Customer, 487–488 CD class, 511 defined, 441 CD drives, 24 derived, 500 CDs (compact discs), 24 designing, 480–491 ceil() function, 237 Dog, 515–516 Central processing unit (CPU) finding, in problems, 481–486 inheritance, 499–520 as computer’s brain, 31 IntVar, 571 defined, 21 Mammal, 514–516 fetch-decode-execute cycle, 32–33 in modules, storing, 451–453 instruction set, 31 polymorphism, 514–520 microprocessor, 21–22 Radiobutton, 570–573 operations, 31 responsibilities, identifying, 486–491 change_me function, 205–207 SavingsAccount, 510, 511 Characters ServiceQuote, 489–491 encoding schemes, 29–30 SUV, 501, 506–508 escape, 85–86 Truck, 505–508 extraction from string, 366–368 UML layout, 481 individual, 358–362 Code line continuation, 82 Coin class example, 443–449 newline, 83–84, 340 debugging, 122 in password, validating, 374–377 defined, 37 selecting range of, 365–366 modularized program, 184 space, 69 responding to exceptions, 296–298 storage, 29 validation, 234 string, accessing, 358–362 Command line interfaces, 545–546 whitespace, 370, 372 Comments Character sets, ASCII, 595 defined, 57 Charts, IPO, 228–229 end-line, 57–58 Checkbuttons, 548, 574–576 importance of, 58 Checkbutton widget Compilers, 36–37 creating, 574 Computers defined, 548 components, 20–25 use example, 574–576 CPU, 21–22 Class definitions data storage, 25–30 Coin example, 443–449 defined, 442
616 Index Data types bool, 129 Computers (continued ) conversion and mixed-type expressions, ENIAC, 21, 22 81–82 input devices, 24 and literals, 64–65, 131 main memory, 23 mixing, 392–393 output devices, 24 str, 65–66 secondary storage devices, 23–24 user interface, 545 Debugging, 50, 122 global variables and, 210–211 Concatenation defined, 362 Decision structures, 100 list, 315–316 actions performed in, 100–101 newline to string, 263–269 combining sequence structures with, 115–116 + = operator in, 316, 363 dual alternative, 108 string, 86, 362–363 in flowcharts, 100 if-elif-else statement, 121–122 Conditional execution if-else statement, 108–111 if-else statement, 109 if statement, 99–107 inside, 116 Condition-controlled loops. See also Loops nested, 115–123 defined, 140, 176 single alternative, 100 while loop, 140–148 Degrees() function, 237 Contact class example, 470–480 del statement, 327 Continuation character, 82 Depth of recursion, 528 Control structures, 99, 115 Derived classes, 500 Convert button, 560, 562 Dialog boxes Cookies, 254, 442 Copying lists, 328–330 defined, 545 cos() function, 237 illustrated, 546 Count-controlled loops, 140, 148–158. See info, 556–559 Dictionaries also Loops creating, 388 C# programming language, 35 defined, 387 Customer class, 487–488 elements, adding, 390 elements, deleting, 391, 395 D elements, display order, 388 Data elements, number of, 391–392 empty, creating, 393–394 appending to files, 266 example, 400–403, 403–409 binary file, 255 iteration, 394–395 digital, 30 keys, 387, 388 hiding, 438 key-value pairs, 387–390 output, 83–91 methods, 395–400 processing, 277–290 mixing data types in, 392–393 reading from files, 254–255, 260–263 parts of, 387 text file, 255 retrieving value from, 388–389 writing to files, 254, 258–260 storing objects in, 470–480 Data attributes, 438 values, 389–390 hidden, 439 Dictionary views hiding, 448–451 defined, 396 initializing, 444 elements, 396 instance, 458–480 Data storage, 25–29 characters, 29 music, 30
Index 617 keys returned as, 397 with try/except statement, 301–302 values returned as, 399–400 Exception objects, 303 dict() method, 394 Exceptions difference method, 416–417 Digital data, 30 catching all, with one except clause, Digital devices, 30 298–299 Direct access files, 256, 287, 290 Direct recursion, 532 code response to, 292 discard method, 413 default error message display, 299–300 Disk drives defined, 71, 290 defined, 23 IndexError, 312–313, 361 program storage on, 32 IOError, 295–296, 298, 302 Divide and conquer approach, 184 KeyError, 389, 391, 413 Division multiple, 296–298 floating-point, 74 unhandled, 302–303 integer, 72, 74 ValueError, 293–294, 298, 299, 300, 302, / operator, 72, 74, 75 Dog class, 515–516 326 Dot notation, 215, 237 ZeroDivisionError, 302 Dual alternative decision structure, 107–108 Execution, 177 dump method, 423 in fetch-decode-execute cycle, 32 DVD drives, 24 pausing, 196 DVDs (digital versatile discs), 24 Python interpreter, 588–589 try/except statement, 293 E while loop, 167 else clause, 111, 118 Exercises decision structures, 134–137 execution, 108 dictionaries and sets, 433–435 with try/except statement, 301–302 files and exceptions, 310–312 else suite, 301 GUI programming, 580–581 Encapsulation, 438 inheritance, 522–523 end–of–file, 426–427, 469 input, processing, and output, 95–97 endswith method, 373, 374 introduction, 46–47 ENIAC computer, 21, 22 lists and tuples, 352–354 Entry widget modules, 245–247 defined, 548, 559 programming, 494–497 getting input with, 559–562 recursion, 542–543 use example, 560–562 repetition structures, 217–219 Error handlers, 167 strings, 384–386 Error messages, 37, 40 exp() function, 237 default, displaying, 299–300 Exponent (**) operator, 72, 76–78 loop displaying, 166–167 traceback, 293, 295 F Errors. See Exceptions Factorial function, 530–531 Error traps, 167 Factorials Escape characters, 85–86 Event handlers, callback functions as, 556 calculation with recursion, 528–532 Exception handling definition rules, 532, 535 defined, 296 Fetch-decode-execute cycle, 32–33 multiple exceptions, 296–299 Fibonacci series defined, 533–534 recursive function calculation, 534–535
618 Index iterations, user control, 156–158 range function with, 148–152 Field widths target variables, 152–156 columns, 89 format function, 87, 90 minimum, specifying, 89–90 Format specifiers, 87–90 Formatting File modes, 261 with comma separators, 88–89 Filename extensions, 256 floating-point number as File objects percentage, 90 close method, 259, 423 integers, 90–91 defined, 256 numbers, 86–87 read method, 260–263 in scientific notation, 88 variable name referencing, 256–258 for statement, 148 writelines method, 339–342 FORTRAN, 35 write method, 258 Frame widget, 548, 555 finally clause, with try/except statement, Function call defined, 187 302 examples of, 188, 189 Finally suite, 302 in flowcharts, 192 find method, 374 nested, 70 Flags, 130 process, 187–190 Flash drives, 24 recursive, 528 Flash memory, 24 Function definitions float data type, 65, 81–82 block, 188 float() function, 69, 70, 71, 82 defined, 186 Floating-point division, 74, 75 function header, 186 Floating-point notation, 29 general format, 186–187 Floating-point numbers, 90 Function headers, 186, 190, 200, 204 floor() function, 237 Functions, 327–328 Floppy disk drives, 23 acos(), 237 Flowchart, 52 asin(), 237 atan(), 237 clock simulator, 171 Boolean. See Boolean functions decision structure, 100, 101, 105 callback. See Callback functions dual alternative decision structure, 108 calling. See Calling functions input validation loop, 166 ceil(), 237 logic for file end detection, 272 cos(), 237 nested decision structure, 117, 120 degrees(), 237 pay calculating program, 53 exp(), 237 program development cycle, 49 factorial, 530–531 running total calculation, 159 float(), 69, 70, 71, 82 sequence structure nested inside decision floor(), 237 format, 87, 90 structure, 116 hypot(), 237 sequence structures with decision structure, input, 67–70 int(), 69–71 115–116 is_even, 233 while loop, 141 isinstance, 517–520 for loops. See also Loops len, 313, 362, 391–392 as count-controlled loops, 148–158 defined, 148–149 iterating lists with, 312 iterating over dictionaries with, 394–395 iterating over list of strings with, 150 iterating over sets, 414 iterations, 156–158
Index 619 library, 213–215 getting input with, 559–562 list(), 310–311, 348 info dialog boxes, 556–559 load, 423, 424 Label widgets, 550–553 log(), 237 radio buttons, 570–573 message, 187–192, 525–527 sketch of window, 566–567 min, 327–328 text display, 550–553 open, 257, 258, 262 with tkinter module, 547–550 print. See print function widget list, 567 radians(), 237 widget organization, 553–556 randint, 215–218, 220 range. See range function H range_sum, 532–533 Hardware, 20–25 recursive. See Recursive functions set, 411 components, 20–21 showinfo, 556 defined, 20 sin(), 237 Hierarchy charts, 193–194, 202. See also sqrt(), 237 sum, 225–226 Program design tan(), 237 High-level programming languages, 34–36 type, 65 hypot() function, 237 value-returning. See Value-returning I functions IDLE. See Integrated development G environment GCD (greatest common divisor), 535–536 if-elif-else statement, 121–122. See also Generalization, 499–500 get method, 396, 476, 559–560, 562, 565, Decision structures if-else statement. See also Decision 573 Getters, 463 structures Global constants, 345 conditional execution in, 109 defined, 107 defined, 211 general format, 108 using, 211–213 indentation, 109 Global variables. See also Variables nested, 122, 126 accessing, 209 use of, 109–110 creating, 210 if statement, 99. See also Decision debugging and, 210–211 defined, 209 structures examples of, 209–210 Boolean expression testing, 101–104 functions using, 211 execution, 99 program understanding and, 211 general format, 99 use restriction, 210–211 nested blocks, 106–107 Greatest common divisor (GCD), 535–536 use example, 104–106 GUI programs use of, 106–107 Button widgets, 556–559 import statement, 214–215, 218 check buttons, 574–576 Indentation creating, 547–550, 566 IDLE, automatic, 591–592 Entry widget, 559–562 IDLE, default, 592 as event-driven, 547 if-else statement, 109 fields, 562–566 nested decision structures, 118 in Python, 190–191 IndexError exception, 312–314, 361. See also Exceptions
620 Index randrange function return, 222 Integrated development environment Indexes characters, 360 (IDLE), 42 defined, 312 automatic indentation, 591–592 invalid, 319, 322, 361, 366 color coding, 591 with lists, 313–314 defined, 41 negative, 312, 319, 322, 361, 366 indentation, 190–191 position reference, 319, 366 programming environment, 583 in slicing expression, 318 Python Shell window, 587–589, 591, string, 360–361 tuples support, 347 593–594 resources, 594 index method, 323–325 running programs in, 593–594 Indirect recursion, 532 saving programs in, 592 Infinite loops, 147 shell window, 588 Info dialog boxes, 556–557, 559, 562–563, software bundling, 587 starting, 587–589 573–574 statement execution, 588 Inheritance text editor, 41 tkinter module, 547 defined, 499 writing Python programs in, 589–590 generalization and, 499 Interactive mode, 39–41, 54, 65, 71, 84, 87, and “is a” relationship, 500–508 specialization and, 499 102, 218–219, 315–316–319 in UML diagrams, 508–509 Interpreters using, 509–513 Initializer methods, 444 defined, 36 in operator high-level program execution, 37 general format, 320 Python, 38 searching list items with, 320–321 intersection method, 416 testing dictionary values with, 389–390 Intersection of sets, 416 testing set values with, 414–415 int() function, 69–71 testing strings with, 369 IntVar class, 571 Input IOError exceptions, 295–296, 298, 302 in computer program process, 53–54 IPO charts, 228–229 defined, 24 isalnum() method, 370 with Entry widget, 559–562 isalpha() method, 370 flowchart symbols, 52 isdigit() method, 370 reading from keyboard, 67–71 is_even function, 233 Input devices, 24 isinstance function, 517–520 Input files, 254–255 islower() method, 370 input function, 67–70 isspace() method, 370 Input validation loops, 165–169. See also issubset method, 418 issuperset method, 418 Loops isupper() method, 370 insert method, 325 item separators, 84–85 Instances, working with, 458–480 items method, 396–397 Instructions, 31–33 iterable, 150–151, 158, 175–176, 310–311 Instruction sets, 31, 33 Iteration, loop, 147, 150 Integer division, 72, 74–75 nested loops, 175–176 Integers and sentinel, 163 user control, 156–158 formatting, 90–91 list of, 310 randint function return, 220
Index 621 J as dynamic structures, 309 Java, 35 elements, 310 JavaScript, 35 finding items in, 320–321 indexing, 312–313 K index method and, 323–325 Keyboard, reading input from, 67–71 insert method and, 325 KeyError exceptions, 389, 391, 413, 414 of integers, 310 Keys. See also Dictionaries items, adding, 321–323 items, in math expressions, defined, 387 dictionary views and, 396–397 330–331 different types of, 393 items, inserting, 325 duplicate, 390 items, removing, 326–327 string, 388 items, reversing order of, 327 types of, 388 items, sorting, 325–326 keys method, 397, 410 iterating with for loop, 312 Key-value pairs as mutable, 313–315 adding, 390 passing as argument to functions, defined, 387 deleting, 391 333–334 as mappings, 388 processing, 330–342 removing, 398, 399 recursion, 532–533 returning, 399 remove method and, 326–327 Keyword arguments, 207–209 returning from functions, 334–336 Key words, 34–35, 50, 61, 186–187, 239 reverse method and, 327 slicing, 317–320 L sort method and, 325–326 Label widget storing objects in, 464–466 of strings, 310 creating, 555 tuples versus, 346 defined, 548 two-dimensional, 342–346 as output fields, 562–566 values, totaling, 332 pack method, 551 working with, 339–342 stacked, 552 writing to files, 341 text display with, 550–553 Literals Latin Subset of Unicode, 595 numeric, 65 len function, 313, 362, 391–392 string literals, 55–56, 63, 85–86, 153, 258, Library functions, 213–215 Listbox widget, 548 263, 358, 369 list() function, 310–311, 348 load function, 423, 424 Lists Local variables, 197–199, 206, 235, 528. See accepting as an argument, 327, 328 append method and, 321–323 also Functions; Variables concatenating, 315–316 log() function, 237 contents, displaying, 345 Logical operators converting iterable objects to, 310–311 converting to tuples, 348 and, 124–126 copying, 328–330 defined, 123 defined, 186, 309, 310 expressions with, 123 of different types, 310 not, 123, 125 displaying, 310 numeric ranges with, 128 or, 123–125 types of, 123 Logic errors, 50
622 Index Method overriding, 514 Microprocessors, 21–22 Loops min function, 327–328 for, 148–158, 273–277, 312, 358, Mixed-type expressions, 81–82 394–395, 397, 400, 414 Mnemonics, 33 condition-controlled, 140–148 Modification methods, 372–373 count-controlled, 148–158 Modifying records, 285–286 end of files and, 426–427 Modularization, 238 infinite, 147 Modularized programs, 184–185 input validation, 203–208 Module Docs, 583 iteration, 147, 156, 163 Modules nested, 170–176, 345 pretest, 144–145 benefits of, 238 priming read, 166 defined, 214, 238 recursion versus, 539 function, 229–232 sentinels and, 162–164 importing, 239 validation, 234 math, 235–237 while, 140–148 pickle, 423 random, 215, 218, 221 lower() method, 372–373 rectangle, 239–240 Low-level languages, 34 storing classes in, 451–453 lstrip() method, 372 storing functions in, 238–242 tkinter, 547–550 M using, 239 Machine language, 30–34, 36–37, 50 Modulus operator. See Remainder (%) operator Main memory Multiple assignment, 399 Multiple items defined, 23 displaying with + operator, 86 programs copied into, 32–33 displaying with print function, 63 Mammal class, 514–516 separating, 84–85 Math expressions Multiplication (*) operator, 72, 75, 311 algebraic, 79–80 Mutable, lists as, 313–315 defined, 71 Mutator methods, 463 list elements in, 330–331 mixed-type, 81–82 N operands, 72 Negative indexes, 312, 319, 361, 366 parentheses, grouping with, 76–77 Nested blocks, 118–119 randint function in, 215–216 Nested decision structures, 117–122 simplifying with value-returning functions, Nested function calls, 70 Nested lists. See Two-dimensional lists 224–228 Nested loops, 170–176, 345. See also Loops Math module, 235–238 Newline (\\n) character Math operators concatenating to a string, 263–264 defined, 71 stripping from string, 264–266, 340 list of, 72 suppressing, 83–84 max function, 327–328 not in operator Memory in list item determination, 321 buffer, 259 testing dictionary values with, 389–390 flash, 24 testing set values with, 414–415 main memory, 23 testing strings with, 369 random access (RAM), 23 Memory sticks, 24 Menubutton widget, 548 Menu-driven programs, 242
Index 623 not operator, 123, 125 in. See In operator Nouns, list refining, 483–486 addition (+), 72, 75, 86 Numbers assignment, 103, 161–162 augmented assignment, 161–162 advanced storage, 30 exponent (**), 72, 76–78 binary, 27–28 logical. See Logical operators factorial of, 529–531 math, 71–72 Fibonacci, 533–535 multiplication (*), 72, 75, 311 floating-point, 29, 90 not in. See Not in operator formatting, 86–87 or, 123–125, 127, 128 pseudorandom, 222–223 precedence, 75 random, 214–223 relational, 101–102, 113–114 running totals, 159–162 remainder (%), 72, 75, 78–79 storage, 27–29 repetition (*), 311, 378–379 Numeric literals, 65 subtraction (-), 72, 75 Numeric ranges, with logical operators, 128 Optical devices, 24 or operator, 123–125, 127, 128 O Output Object-oriented programming (OOP) in computer program process, 53–54 data, 83–91 class design, 480–491 defined, 24 classes, 441–458 displaying, 54–57 data hiding, 438 Output devices, 24 defined, 438 Output files, 254, 255, 259, 266, 270 encapsulation, 438 Overhead, 528 instances, 441, 458–480 Overriding, method, 514 Objects, 555. See also Classes characteristics description, 441 P defined, 438 pack method, 551–553, 555, 560 dictionary, 387–410 Parameter lists, 204 everyday example of, 439–440 Parentheses, grouping with, 76 exception, 303 Pascal, 35 file, 260–261 Passing arguments. See also Arguments list, 309, 310 “is a” relationship, 500 to function, 200–203 passing as arguments, 466–467 function parameter variable, 205–207 pickling, 468–470 to index method, 323–325 reusability, 439 list as function, 333–334 sequence, 309 multiple, 203–205 serializing, 422–428 and objects, 466–467 set, 410–422 by position, 204 storing in dictionaries, 470–480 by value, 207 storing in lists, 464–466 Passwords, validating characters in, StringVar, 562–563 unpickling, 469–470 374–377 OK buttons, 556, 558, 571, 573 Path variable, adding Python directory to, open function, 257, 258, 262 Operands, 72 584–585 Operating systems, 24 Pattern printing using nested loops, 173–176 Operators Percentages, calculations, 73–74 and, 124–126 Pickle module, 423–424, 468, 473 Pickling, 422–424, 426, 468–470
624 Index task breakdown, 50–51 top-down, 192–193 pi variable, 237 with while loops, 145–147 Pixels, 30 Program development cycle, 49–50 Polymorphism Programmers comments, 57–58 behavior, ingredients of, 514 customer interview, 51 defined, 514 defined, 19 isinstance function, 517–520 task breakdown, 51 popitem method, 399, 403 task understanding, 51 pop method, 398, 608 Programming Positional arguments, 209 GUI, 545–581 Precedence, operator, 75 in machine language, 33–34 Pretest loops object-oriented (OOP), 437–497 defined, 144 procedural, 437–438 while loops as, 144–145 with Python language, 19–20 Priming reads, 166, 274 Programming languages, 35, 545–581. See also print function ending newline suppression, 83–84 Python multiple item display with, 63 Ada, 35 output display with, 54–57 assembly, 33 Private methods, 440 BASIC, 35 Problem domain C/C++, 35 defined, 482 COBOL, 35 nouns/noun phrases in, 482–483 FORTRAN, 35 writing description of, 482–483 high-level, 34–35 Problem solving Java, 35 base case, 529 JavaScript, 35 with loops, 528 low-level, 34 with recursion, 528–532 Pascal, 35 recursive case, 529 Ruby, 35 Procedural programming Visual Basic, 35 defined, 437 Programs focus of, 437 assembly language, 33 vs. object-oriented programming, 438 compiling, 36–37 Procedures, 339, 437–438 copied into main memory, 32–33 Processing files, 259 defined, 19 Processing lists, 330–342 exceptions, 290–303 an argument to function, 333–334 execution, pausing, 196 average of values in, 332–333 flowcharting, with functions, 191–192 and files, 339–342 functioning of, 30–37 from function, returning, 334–336 image editing, 20 total of values in, 332 menu driven, 242 Processing symbols, 52 modularized, 184–185 Program design, 49–53 record deletion, 288–290 in development cycle, 49–50 record modification, 285–286 flowcharts, 52–53, 191–192 running, 21, 593–594 with functions, 191–196 saving, 592 hierarchy charts, 193 storage, 32 with for loops, 192–194 testing, 38 pseudocode, 52 steps, 49–50
Index 625 delete_coffee_record.py, 292–293 transfer, control of, 190 dice.py, 219 utility, 25 display_file.py, 294–295 word processing, 20, 23, 25 display_file2.py, 295–296 writing in IDLE editor, 41, 589–590 division.py, 290–291 Programs (this book) dollar_display.py, 88–89 account_demo.py, 512–513 drop_lowest_score.py, 336–339 accounts.py, 510, 511 empty_window1.py, 548–549 account_test.py, 454–455 empty_window2.py, 549–550 account_test2.py, 457–458 endless_recursion.py, 525–526 acme_dryer.py, 195–196 fibonacci.py, 534–535 add_coffee_record.py, 281–282 file_read.py, 260–261 animals.py, 514–515, 516 file_write.py, 259–260 auto_repair_payroll.py, 110 formatting.py, 86–87 average_list.py, 333 frame_demo.py, 554–555 bad_local.py, 197 function_demo.py, 187–188 bankaccount.py, 453 gcd.py, 535–536 bankaccount2.py, 456–457 generate_login.py, 367–368 barista_pay.py, 330–331 geometry.py, 240–242 birds.py, 198–199 global1.py, 209–210 birthdays.py, 404–409 global2.py, 210 button_demo.py, 556–557 grader.py, 120–121 card_dealer.py, 401–403 gross_pay.py, 203 car_demo.py, 504–505 gross_pay1.py, 292–293 car.py, 489 gross_pay2.py, 293–294 car_truck_suv_demo.py, 507–508 gross_pay3.py, 299–300 cell_phone_list.py, 464–466 hello_world.py, 550–551 cellphone.py, 461–462 hello_world2.py, 552 cell_phone_test.py, 461–463 hello_world3.py, 552–553 change_me.py, 205–206 hypotenuse.py, 236–237 checkbutton_demo.py, 574–576 index_list.py, 324 circle.py, 238–239 infinite.py, 147 coin_argument.py, 467 in_list.py, 320–321 coin_demo1.py, 445–446 input.py, 70–71 coin_demo2.py, 448–449 keyword_args.py, 207–208 coin_demo3.py, 449–451 keywordstringargs.py, 208 coin_demo4.py, 452 kilo_converter.py, 560–562 coin_demo5.py, 459 kilo_converter2.py, 563–565 coin.py, 451–452 list_append.py, 322–323 coin_toss.py, 220–221 loan_qualifier.py, 117–118 columns.py, 89–90 loan_qualifier2.py, 126–127 commission.py, 142 loan_qualifier3.py, 127–128 commission2.py, 184 login.py, 366–367, 375–377 commission_rate.py, 230–232 modify_coffee_records.py, 286–287 concatenate.py, 363–364 multiple_args.py, 203–204 contact_manager.py, 472–480 no_formatting.py, 86–87 contact.py, 471 pass_arg.py, 200 count_Ts.py, 360 password.py, 111–112 cups_to_ounces.py, 202–203 pickle_cellphone.py, 468–469 customer.py, 488
626 Index string_test.py, 371 string_variable.py, 66 Programs (this book) (continued ) strip_newline.py, 269–270 pickle_objects.py, 424–426 sum_numbers.py, 160 polymorphism_demo.py, 517–518 temperature.py, 146–147 polymorphism_demo2.py, 519–520 test_average.py, 106–107 property_tax.py, 163–164 test_averages.py, 568–570 quit_button.py, 558–559 test_score_average.py, 77 radiobutton_demo.py, 571–572 test_score_averages.py, 172–173 random_numbers.py, 216, 345 time_converter.py, 78–79 random_numbers2.py, 216–217 total_ages.py, 225 read_emp_records.py, total_function.py, 334 280–281 total_list.py, 332 read_list.py, 340–341 towers_of_hanoi.py, 538–539 read_number_list.py, 342 triangle_pattern.py, 175 read_number.py, 269 two_functions.py, 188–189 read_running_times.py, 276–277 unpickle_cellphone.py, 469–470 read_sales.py, 273 unpickle_objects.py, 426–428 read_sales2.py, 274 user_squares1.py, 156–157 rectangle.py, 240 user_squares2.py, 157–158 rectangular_pattern.py, 212–213 validate_password.py, 377 repetition_operator.py, 378–379 variable_demo.py, 60 retail_no_validation.py, 168 variable_demo2.py, 60 retail_with_validation.py, 169 variable_demo3.py, 63 return_list.py, 334–335 variable_demo4.py, 63–64 sale_price.py, 73–74, 227–228 vehicles.py, 501–502, 503, 505, 506 sales_list.py, 314–315 writelines.py, 339 sales_report1.py, 296 write_list.py, 340 sales_report2.py, 298–299 write_names.py, 264 sales_report3.py, 300 write_number_list.py, 341 sales_report4.py, 301–302 write_numbers.py, 267 save_emp_records.py, 300–283 write_sales.py, 270–271 save_running_times.py, 275–276 wrong_type.py, 518 search_coffee_records.py, 284 Pseudocode, 52 servicequote.py, 490–491 Pseudorandom numbers, 222–223 sets.py, 419–421 Public methods, 440 show_coffee_records.py, 282–283 Python simple_loop1.py, 149 defined, 35 simple_loop2.py, 150 directory, adding to Path variable, 584–585 simple_loop3.py, 150 execution by, 589 simple_loop4.py, 151 IDLE, 41–42, 587 simple_math.py, 72–73 installing, 38, 583 sort_names.py, 114 interactive mode, 39–40 speed_converter.py, 155–156 interpreter, 37, 39 split_date.py, 380 interpreter execution, 584 square_root.py, 236 key words, 35 squares.py, 153 in learning programming, 19–20 stair_step_pattern.py, 176 script mode, 40–41 string_args.py, 205 Shell window, 587, 588, 594 string_input.py, 68 string_split.py, 379
Index 627 uninstalling, 583 iterable object, converting to list, 150–151, Python Manuals, 583 310–311 Python programs with for loop, 150–152 group, 583 Raw string, 262 running, 41 Read, priming, 166, 272 writing in IDLE editor, 589–590 Reading writing in script mode, 40–41 data from files, 255, 260–263 Q files with loops, 271–273 Quit button, 558–561 input from keyboard, 67–69 with for loop, 273–274 R numbers from text files, 268 radians() function, 237 numbers with input function, 69–71 Radio buttons numeric data, 267–270 records, 279 defined, 570 strings, and stripping newline, 264–266 group of, 570 readline method illustrated, 570 defined, 261 use example, 571–573 empty string return, 272 uses, 570 example use, 261–262 Radiobutton widget reading strings from files with, 269 callback functions with, 573 return, 261, 263 creation and use example, 570–573 readlines method, 340 defined, 548 read method, 260–261 as mutually exclusive, 571 Read position RAM. See Random access memory (RAM) advanced to the end of file, 263 randint function advance to next line, 262–263 calling, 215 defined, 262 defined, 215 initial, 262 in interactive mode, 218 Records in math expression, 220 adding, 281–283 random number generation, 216–218 defined, 277 return value, 215–216 deleting, 288–290 use examples, 217–218 displaying, 281–283 Random access files, 256 fields, 278 Random access memory (RAM), 23 files, 278 random module, 215, 221, 222–223 modifying, 285–287 Random numbers processing, 277–290 displaying, 217 programs storing, 281 example uses, 214–215 searching, 283–285 generating, 214–218 writing to sequential access files, 278 interactive mode, 218 Recursion pseudo, 222–223 depth of, 528 to represent other values, 220–221 direct, 532 seeds, 222–223 in factorial calculation, 529–531 using, 218–219 indirect, 532 range function list elements with, 532–533 arguments passed to, 151–152 loops vs., 528–529, 539 default, 151 problem solving with, 528–532 generation, 151 stopping of, 531
628 Index result variable and, 226, 235 using, 226 Recursive algorithms reverse method, 322, 327 designing, 529 Rounding, 74 efficiency, 528 rstrip() method, 265, 372 examples of, 532–539 Ruby, 35 Fibonacci series, 533–535 Running programs, 593–594 greatest common divisor, 535–536 Running totals recursive call, 531 calculating, 159–162 summing range of list elements, 532–533 defined, 159 Towers of Hanoi, 536–539 elements for calculating, 159 example, 160 Recursive case, 529 logic for calculating, 159 Recursive functions S call, 528 Samples, 30 defined, 525 Saving programs, 592 efficiency, 539 SavingsAccount class, 510, 511 example, 525–528 Scale widget, 548 functioning of, 529 Scientific notation, 88 overhead, 528 Scope Relational operators defined, 101 defined, 197 in string comparisons, 113–114 local variables and, 197–199 types of, 102 parameter variable, 201 Remainder (%) operator Script mode, running programs in, 41 defined, 72, 78 Scrollbar widget, 548 precedence, 75 Searching use example, 78–79 lists, 320–321 remove method, 322, 326–327, 413–414 records, 283–285 Repetition operator (*) strings, 373–374 defined, 311 Secondary storage general format, 311, 378 defined, 23 for lists, 311 devices, 23–24 for strings, 378–379 Seeds, random number, 222–223 use example, 378–379 Seed value, 222 Repetition structures. See also Loops Selection structures. See Decision structures defined, 139, 140 Sentinels example, 139–140 defined, 162, 163 flowchart, 144 using, 163–164 introduction to, 139–140 values, 162–163 replace method, 373, 374 Separators Reserved words. See Key words comma, 88–89 Returning item, 84–85 Boolean values, 233–234 split method, 379–380 dictionary values, 398–400 Sequences. See also Lists key-value pairs, 399 accepting as argument, 327–328 lists from functions, 334–336 defined, 309 multiple values, 234–235 length, returning, 313 strings, 232 tuples, 346–348 return statement defined, 224 form, 224
Index 629 Sequence structures development tools, 25 with decision structure, 115 operating system, 24 defined, 99 requirements, 51 example, 99 system, 24–25 nested inside decision structure, 116 types of, 24 structure, 115, 116 utility programs, 25 use in programming, 99–100 Sorting, item list, 325–326 sort method, 322, 325–326 Serializing objects Source code. See Code defined, 422 Specialization, 499–500 example, 424–426, 468–470 split method, 379 pickle module, 422–423 Splitting strings, 379–380 unserializing, 426–428, 469–470 sqrt() function, 237 startswith method, 373, 374 ServiceQuote class, 489–491 Statements set function, 411 for, 148, 152, 154 set method, 566, 573 assignment, 58–61 Sets in blocks, 101, 187 breaking into multiple lines, 82–83 adding elements, 412–413 converting math formulas to, 79–81 creating, 411 defined, 36 defined, 410 del, 327 difference of, 416–417 if, 99–107 duplicate elements, 411 if-elif-else, 115–123 elements, as unique, 410 if-else, 108–111 elements, number of, 412 import, 213–214 elements, removing, 413–414 return, 224–226, 235 intersection of, 416 try/except, 290, 292–293, 298–299, 301, for loop iteration over, 414 operations, 419–421 302 subsets, 418 Step values, 152 supersets, 418 str data type, 65–66 symmetric difference of, 417 str function union of, 415 unordered, 410 defined, 267 values, testing, 414–415 example use, 267 Settings. See Mutator methods String comparisons, 112–115, 372–373, 389, 390 Showinfo function, 556 String concatenation sin() function, 237 defined, 86, 362 Single alternative decision structures, 100 example, 86 Slices interactive sessions, 362 defined, 317 newline to, 263–264 example use, 317–319 with + operator, 86 general format, 317 with + = operator, 363 invalid indexes and, 319 String literals list, 317–320 defined, 55 start and end index, 318 enclosing in triple quotes, 56 string, 365–366 Strings Software characters, accessing, 358–362 application, 25 comparing, 112–116 defined, 19 defined, 55 developers. See programmers
630 Index defined, 36 human language, 37 Strings (continued ) Syntax errors extracting characters from, 366–368 correcting, 50 as immutable, 363–364 defined, 37 indexes, 360–361 reporting, 594 iterating with for loop, 358–360 running programs and, 594 list of, 310 System software, 24–25 method call format, 370 modification methods, 372–373 T operations, 357–364 tan() function, 237 raw, 258 Target variables reading as input, 357 repetition operator (*) with, 378–379 defined, 150 returning, 232 inside for loops, 152–154 search and replace methods, 373–374 use example, 153 slicing, 365–366 Terminal symbols, 52 space character at end, 69 Testing splitting, 379–380 dictionary values, 389–390 storing with str data type, 65–48 programs, 50–51 stripping newline from, 264–266 set values, 414–415 testing, 369 string methods, 370–371 testing methods, 370–371 strings, 369 writing as output, 357 Text written to files, 260 displaying with Label widget, 550–553 editing, 589–590 StringVar object, 562–563 Text files strip() method, 372 defined, 255 Stripping newline from string, 264–266 reading numbers from, 268 Structure charts. See Hierarchy charts Text widget, 548 Subclasses Tkinter module defined, 547 defined, 500 programs using, 548 as derived classes, 500 widgets, 548 method override, 514 Top-down design polymorphism, 514–520 defined, 192 writing, 501 process, 192–193 Subscripts, 344 Toplevel widget, 548 Subsets, 418 Totals Subtraction (-) operator list values, 332 defined, 72 running, 159–162 precedence, 75 Towers of Hanoi. See also Recursive Superclasses as base classes, 500 algorithms defined, 500 base case, 538 in UML diagrams, 508–509 defined, 536 writing, 501 illustrated, 536 Supersets, 418 problem solution, 537–538 SUV class, 506–507 program code, 538–539 Symbols, flowchart, 52 steps for moving pegs, 537 symmetric_difference method, 417 Tracebacks, 291, 295 Symmetric difference of sets, 417 Syntax
Index 631 Truck class, 505–506 and IPO charts, 228–229 Truncation, in integer division, 74 randint and, 215–218 Truth tables random number generation, 214–223 randrange and, 221–222 not operator, 125 returning multiple values, 234–235 and operator, 124 return statement, 224–226 or operator, 124 for simplifying mathematical expressions, try/except statement else clause, 301–302 226–228 execution of, 293 values, 213, 226 finally clause, 302 void functions and, 185 handing exceptions with, 294, 296–297 writing, 224–235 one except clause, 298–299 Values use example, 293–294 Boolean, 233–234 Tuples, 346–348 data attribute, 440 Two-dimensional lists, 342–346. See also Lists dictionaries, 389–390 Two’s complement, 30 global constants, 211 type function, 65 list, averaging, 332–333 list, totaling, 332 U multiple, returning, 234–235 UML diagrams random numbers to represent, 220–221 range of, 128 Customer class, 487 seed, 222 inheritance in, 508–509 value-returning functions, 213, 226 layout, 481 values method, 399–400 ServiceQuote class, 490 Variables Unicode, 29 Boolean, 129–130 Unified Modeling Language (UML), 480 defined, 58, 63 union method, 415 global, 209–211 Union of sets, 415 local, 197–199, 206, 235, 528 update method, 412 math module, 237 upper() method, 372 names, sample, 62 USB drives, 23–24 naming rules, 61–62 User interfaces Path, 584 command line, 545–546 reassignment, 63–64 defined, 545 reassignment to different type, 66 graphical user (GUIs), 545–581 scope, 197–198 Utility programs, 25 statements, 58–61 target, 152 V Visual Basic, 35 Validation W code, Boolean functions in, 234 while loops. See also Loops input, 167 Widgets password characters, 374–377 ValueError, 293–294, 298, 299, 300, 302, arrangement of, 556 Button, 548, 556–559 326 Canvas, 548 Value-returning functions Checkbutton, 548, 574–576 defined, 548 benefits, 226 Entry, 548, 559–562 defined, 213 general format, 224 how to use, 226–228
632 Index writelines method, 339 write method Widgets (continued ) Frame, 548, 555 defined, 258 with frames, organizing, 553–556 format for calling, 258–259 Label, 548, 551–552, 555, 562–566 Writing Listbox, 548 code, 50 list of, 567 data to files, 258, 262–264 Menu, 548 numeric data, 271–273 Menubutton, 548 programs in IDLE editor, Message, 548 Radiobutton, 548, 570–573 589–590 Scale, 548 records, 282 Scrollbar, 548 Text, 548 Z tkinter module, 548 ZeroDivisionError exception, 302 Toplevel, 548
Credits Figure 1.2a pg. 21 © nature photos/Shutterstock “Digital webcam in a white background reflection” Figure 1.2b pg. 21 © Nikita Rogul/Shutterstock “Modern flight joystick isolated on white background” Figure 1.2c pg. 21 © Feng Yu/Shutterstock “Scanner close up shot, business concept” Figure 1.2d pg. 21 © Chiyacat/Shutterstock “Black wireless computer keyboard and mouse isolated on white background” Figure 1.2e pg. 21 © Eikostas/Shutterstock “Compact photo camera” Figure 1.2f pg. 21 © Eikostas/Shutterstock “Computer drawing label with pen” Figure 1.2g pg. 21 © Vitaly Korovin/Shutterstock “Illustration of hard disk drive HDD isolated on white background with soft shadow” Figure 1.2h pg. 21 © Lusoimages/Shutterstock “Small computer speakers isolated on a white background” Figure 1.2i pg. 21 © jocic/Shutterstock “Color printer” Figure 1.2j pg. 21 © Best Pictures/Shutterstock “Four monitors. Vector” Figure 1.2k pg. 21 © Peter Guess/Shutterstock “Stick of computer random access (RAM)” Figure 1.2l pg. 21 © Aquila/Shutterstock “Chip processor radiator” Figure 1.3 pg. 22 Courtesy of US Army Historic Computer Images “The ENIAC Computer” Figure 1.4 pg. 22 © Creativa/Shutterstock “A scientist showing a closeup of a computer chip” Figure 1.5 pg. 23 © Garsya/Shutterstock “Computer memory isolated on a white background” Figure 1.20 and B.1–B.10 pg. 41, pgs. 588–594 Python Software Foundation Figures 6.6 and 6.15 pg. 260, pg. 268 © Microsoft Corporation. Used with permission from Microsoft. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY OF THE INFORMATION CONTAINED IN THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED AS PART OF THE SERVICES FOR ANY PURPOSE. ALL SUCH DOCUMENTS AND RELATED GRAPHICS ARE PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY, WHETHER EXPRESS, IMPLIED, OR STATUTORY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THE SERVICES. THE DOCUMENTS AND RELATED GRAPHICS CONTAINED HEREIN COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED HEREIN AT ANY TIME. PARTIAL SCREEN SHOTS MAY BE VIEWED IN FULL WITHIN THE SOFTWARE VERSION SPECIFIED.
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
- 381
- 382
- 383
- 384
- 385
- 386
- 387
- 388
- 389
- 390
- 391
- 392
- 393
- 394
- 395
- 396
- 397
- 398
- 399
- 400
- 401
- 402
- 403
- 404
- 405
- 406
- 407
- 408
- 409
- 410
- 411
- 412
- 413
- 414
- 415
- 416
- 417
- 418
- 419
- 420
- 421
- 422
- 423
- 424
- 425
- 426
- 427
- 428
- 429
- 430
- 431
- 432
- 433
- 434
- 435
- 436
- 437
- 438
- 439
- 440
- 441
- 442
- 443
- 444
- 445
- 446
- 447
- 448
- 449
- 450
- 451
- 452
- 453
- 454
- 455
- 456
- 457
- 458
- 459
- 460
- 461
- 462
- 463
- 464
- 465
- 466
- 467
- 468
- 469
- 470
- 471
- 472
- 473
- 474
- 475
- 476
- 477
- 478
- 479
- 480
- 481
- 482
- 483
- 484
- 485
- 486
- 487
- 488
- 489
- 490
- 491
- 492
- 493
- 494
- 495
- 496
- 497
- 498
- 499
- 500
- 501
- 502
- 503
- 504
- 505
- 506
- 507
- 508
- 509
- 510
- 511
- 512
- 513
- 514
- 515
- 516
- 517
- 518
- 519
- 520
- 521
- 522
- 523
- 524
- 525
- 526
- 527
- 528
- 529
- 530
- 531
- 532
- 533
- 534
- 535
- 536
- 537
- 538
- 539
- 540
- 541
- 542
- 543
- 544
- 545
- 546
- 547
- 548
- 549
- 550
- 551
- 552
- 553
- 554
- 555
- 556
- 557
- 558
- 559
- 560
- 561
- 562
- 563
- 564
- 565
- 566
- 567
- 568
- 569
- 570
- 571
- 572
- 573
- 574
- 575
- 576
- 577
- 578
- 579
- 580
- 581
- 582
- 583
- 584
- 585
- 586
- 587
- 588
- 589
- 590
- 591
- 592
- 593
- 594
- 595
- 596
- 597
- 598
- 599
- 600
- 601
- 602
- 603
- 604
- 605
- 606
- 607
- 608
- 609
- 610
- 611
- 612
- 613
- 614
- 615
- 616
- 617
- 618
- 619
- 620
- 621
- 622
- 623
- 624
- 625
- 626
- 627
- 628
- 629
- 630
- 631
- 632
- 633
- 634
- 635
- 1 - 50
- 51 - 100
- 101 - 150
- 151 - 200
- 201 - 250
- 251 - 300
- 301 - 350
- 351 - 400
- 401 - 450
- 451 - 500
- 501 - 550
- 551 - 600
- 601 - 635
Pages: