image
imagewidth (px)
1.7k
1.7k
id
stringlengths
13
16
text
stringlengths
0
4.99k
corpus-test-200
270 11 Classes 8. Suppose line 2 is changed to def init () :. What would room_1's attributes be initialized to? a. length = 0, width = 0 b. length = 1, width = 1 C. Error Instance attributes vs. class attributes The attributes shown so far have been instance attributes. An instance attribute is a variable that is uniqu...
corpus-test-201
1.4 String basics 19 a. "wake" + "A" b. "A + wake" C. "A" + "wake" 10. A user enters "red" after the following line of code. color = input ("What is your favorite color?") Which produces the output "Your favorite color is red!"? a. print ("Your favorite color is + color + !) b. print ("Your favorite color is + "color" ...
corpus-test-202
271 | 11.2 Classes and instances | | TRY IT | | Creating a class for an airline's flight tickets | | Write a class, FlightTicket, as described below. Default values follow the attributes. Then create a flight ticket and assign instance attribute with values from input. each read | | Instance attributes: | | flight_ num...
corpus-test-203
272 11 Classes Instance attributes: title:" " author:" year: 0 pages: 0 Class attribute: imprint: Fantasy Tomes Method: init (): initializes the instance attributes print_info (): prints book information (provided in template) Given input: Lord of the Bracelets Blake R. R. Brown 1999 423 A Match of Thrones Terry R. R. ...
corpus-test-204
11.3. Instance methods 273 CHECKPOINT Creating patient vital signs instances Access multimedia content http:///esssoooooooooooooooooooo CONCEPTS IN PRACTICE Defining and using _nit_ with parameters Consider the example above. 1. Suppose the programmer wanted to make blood pressure a required parameter in _iii (). Which...
corpus-test-205
274 11 Classes self.max_mph = max_mph def max_kmh (self): return self.max_mph * 1.609344 def update_max(self, speed) self.max_mph = speed car_1 = ProductionCar((Mccaaenn 'Speedtail', 2020) # car_1.max_mph is 0.0 (rr_luppdatemaxx((2...2 # car_1.max_mph is 250.0 print(cca_1.make, sar_1.model, 'reaches', , tar_l.max_mphy ...
corpus-test-206
11.3. Instance methods 275 order 1. change (False, True) 4. What does order 1 represent at the end of the program? a. 8 oz coffee b. 8 oz coffee with milk C. 8 oz coffee with sugar 5. Why is change () an instance method? a. can change attributes b. has multiple parameters C. can change an instance 6. Can print_order be...
corpus-test-207
276 11 Classes Refilled 100 Current stock: Access multimedia content http Overloading operators Learning objectives By the end of this section you should be able to Identify magic methods and describe their purpose. Develop overloaded arithmetic and comparison operators for user-defined classes Magic methods and custom...
corpus-test-208
11.4 Overloading operators 277 Overloading arithmetic operators Operator overloading refers to customizing the function of a built-in operator. Arithmetic operators are commonly overloaded to allow for easy changes to instances of user-defined classes. CHECKPOINT Overloading _ad__( for a user-defined class, Account Acc...
corpus-test-209
278 11 Classes 6. Which sub () definition overloads the operator for the code below to work? class Pair: def init (self, x=0, y=0) self.x = X self.y = y # Define sub () p1 = Pair(10, 2) p2 = Pair(8, 4) p3 = p1 p2 print (p3.x, p3.y) a. def sub (self): return Pair(self.x other.x, self.y other.y) b. def sub (self, other) ...
corpus-test-210
11.4 Overloading operators 279 11.4 Overloa Overloading | EXAMPLE 11.2 | | | | | comparison operators for the Account class | | | | Code | Output | | | class Account: def init (self, name="", amount=0): self.name name self.amount amount = | | | | def str_((slf)): | | | | return f"{self.name}: [{self.amount)) ...
corpus-test-211
280 11 Classes a. def le_ (other): : return self.amount <= other.amount b. def _e_ (self, other) : return self.amount <= other.amount C. def le_ (self, other) return other.amount <= self.amount 9. Which type of value does gt () return? a. account instance b. Boolean C. integer TRY IT Combining exercise logs The Exercis...
corpus-test-212
20 1 Statements Assigns the string "happy" to a variable, feel. Prints the string "Hi Freda!" with a single print() function using the variable name. Prints the string "I'm glad you feel happy. " with a single print () function using the variable feel. Access multimedia content http://eesaaacciciii/ootorrrrooe Number b...
corpus-test-213
11.5 Using modules with classes 281 int) returns True if my_var is an integer. Expand the existing Account example so that the addition operator can also be used to add an integer value to an Account s amount attribute. Access multimedia content httt:///ott...ooooorotooooooooot 1114ooeeroodiing-pprararrrs) Using module...
corpus-test-214
282 11 Classes Using aliases Aliasing allows the programmer to use an alternative name for imported items. Ex: import triangle as tri allows the program to refer to the triangle module as tri. Aliasing is useful to avoid name collisions but should be used carefully to avoid confusion. EXAMPLE 11.3 Using aliasing to imp...
corpus-test-215
11.6 Chapter summary 283 C. rogue_ level chhaaattrr game_char. . Level() 5. Which code creates a name collision? a. character = 'Ranger' b. Game_char = 'Ranger' C. game_char = 'Ranger' TRY IT Missing import statement Add the missing import statement to the top of the file. Do not make any changes to the rest of the cod...
corpus-test-216
284 11 Classes | Construct | Description | | Class definition | class ClassName: | | | class ClassName: def init (self): # Initialize attributes | | Attributes | class ClassName: class_attr_2 [value] = instance attr 2 [value] instance_attr_ [value] class_attr 1 [value] def __it_ (self): instance attr 1 [value] | | Met...
corpus-test-217
11.6 Chapter summary 2 | Construct | Description | | | class ClassName: # 0ther methods | | Overloaded multiplication operator | def __mul_(selff other): return ClassName (welf. instance_attr ather.instance_attr22 | | Import class from module with alias | from class_module import ClassName as ClassAlias | Tahlo 11 Cha...
corpus-test-218
286 11 Classes Access for free at openstax.org
corpus-test-219
Recursion Figure 12.1 credit: modification of work "Rings from the Ocean", by Sue Corbisez/Flicky CC BY 2.0 Chapter Outline 12.1 Recursion basics 12.2 Simple math recursion 12.3 Recursion with strings and lists 12.4 More math recursion 12.5 Using recursion to solve problems 12.6 Chapter summary Introduction Recursion i...
corpus-test-220
288 12 Recursion CHECKPOINT Three Towers Access multimedia content http:///eeesoooooooooooooooooooo CONCEPTS IN PRACTICE Three Towers and recursion 1. How is the problem of moving two rings solved using recursion? a. Move the small ring to the middle tower, move the bigger ring to the target tower, and move the small r...
corpus-test-221
12.2 Simple math recursion 289 5. How many total steps does it take to solve three rings? a. 3 b. 4 C. 7 6. How many total steps does it take to solve four rings? a. 15 b. 7 C. 3 Simple math recursion Learning objectives By the end of this section you should be able to Identify a recursive case and a base case in a rec...
corpus-test-222
290 12 Recursion 3. Listing the primary numbers (prime numbers) greater than 3. 4. Listing the Fibonacci sequence of numbers. Defining a recursive function Recursive algorithms are written in Python as functions. In a recursive function different actions are performed according to the input parameter value. A critical ...
corpus-test-223
OpenStax Rice University 6100 Main Street MS-375 Houston, Texas 77005 To learn more about OpenStax, visit https://openstax.org. Individual print copies and bulk orders can be purchased through our website. 02024 Rice University. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution 4.0 ...
corpus-test-224
1.5 Number basics 21 What is the type of the following value? "12.0" a. string b. int C. float Basic arithmetic Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication and division. Four basic arithmetic operators exist in Python: 1. Addition (+) 2. Subtraction (-) 3....
corpus-test-225
12.2 Simple math recursion 291 elif n 0: return n return n else: return n * rec_fact(n 1) a. 355687428096000 b. 0 C. no result / infinite computation 7. def rec_fact(n): ifn < 0: print ("error") elif n == 0: return 1 else: return n * rec_fact(n 1) a. 355687428096000 b. 0 c. no result infinite computation 8. def rec_fac...
corpus-test-226
292 12 Recursion TRY IT Write a program that computes the sum of the digits of a positive integer using recursion. Ex: The sum of the digits of 6721 is 16. Hint: There are 10 base cases, which can be checked easily with the right condition. Access multimedia content hhtp://oooaaaa/////o/oooooooopmo 122-simpll-maahh-ecc...
corpus-test-227
12.3 Recursion with strings and lists 293 palindrome (word strip (word [0])). a. Nothing. The function would work the same: the first and last letter would be removed. b. Some words, such as "madamm", would be incorrectly recognized as a palindrome. Recursion with lists The animation below shows a recursive way to chec...
corpus-test-228
294 12 Recursion a. True b. False 8. list 1 = [1, 2, 3] list _ = [1, 2, 3] a. True b. False TRY IT Remove duplicates Write a recursive rem_dup() function that removes duplicates from a list. Ex: List [5, 5, 2, 1, 3, 1, 6] should result in an output list [5, 2, 1, 3, 6]. Access multimedia content http://ghn.aaaaoooooooo...
corpus-test-229
12.4 More math recursion 295 Recursive Fibonacci function def fib(n) # Base case if n == 0 or n == 1: return n # Recursive case elif n > 1: return fib(n - 1) + fib - 2) # Error case else: print ("Fibonacci numbers begin at 0. ") return # &Test code print (fib (7) The above code's output is: CHECKPOINT Recursive Fibonac...
corpus-test-230
296 12 Recursion a. tree b. recursion tree C. iteration tree Greatest common divisor (GCD) The greatest common divisor (GCD) of two positive integers is an integer that is a divisor for both integers. Ex: The GCD of 6 and 9 is 3 because 3 x 2 6, and 3 x The GCD is found easily using Euclid's method. Euclid's method rec...
corpus-test-231
12.5 Using recursion to solve problems 297 5. How many recursive calls are made with gcd (24, 30)? a. 4 b. 1 24 6. What is the GCD of 13 and 23? a. 13 b. 1 C. 23 7. How many recursive calls are made with gcd (13, 23)? a. 1 b. 8 C. 13 TRY IT Write a recursive power () function, such that given an integer x and a positiv...
corpus-test-232
298 12 Recursion Binary search Searching a sorted list usually involves looking at each item. If the item being searched is not found, then the search can take a long time. A binary search is a recursive algorithm used to efficiently search sorted lists. In each recursive step, about half the items are discarded as not...
corpus-test-233
12.5 Using recursion to solve problems 299 The above code's output is: 8 Not found CHECKPOINT Access multimedia content tttttst///ottoooooooooooooppoeeo CONCEPTS IN PRACTICE Binary search 1. Which list can be searched with the binary search algorithm? a. [5, 2, 7, 1, 8] b. [9, 8, 7, 6, 5] C. [4, 5, 6, 7, 8] 2. If the b...
corpus-test-234
300 12 Recursion EXAMPLE 12.4 Solving N towers The solution to Three Towers is simple with recursion. In the code below, rings are numbered from the top down. The smallest ring is 1, the next ring is 2, and when solving for three rings, the bottom ring is 3. Solving the towers problem recursively def three_towers (N, s...
corpus-test-235
22 1 Statements C. 2.5 2.9 6. What is the output of print (x / z)? a. 3 b. 3.0 C. 3.5 7. What is the output of print(y / z)? a. 0 b. 10 C. 10.0 8. What is the output of print (z * 1.5)? a. 2 b. 3 C. 3.0 Operator precedence When a calculation has multiple operators, each operator is evaluated in order of precedence. Ex:...
corpus-test-236
12.6 Chapter summary 301 CONCEPTS IN PRACTICE Solving Three Towers 5. For four rings, how many total lines will be printed by three_towerd () a. 7 b. 15 6. Would an iterative solution to the Three Towers problem be more complex or less complex? a. more complex b. less complex TRY IT Coin combinations Write a recursive ...
corpus-test-237
302 | 12 Recursion | | | At this point, you | should be able to solve problems using recursion. | | Function | Description | | count (element) | Returns the number of times the element exists on the list on which the count () function called. is | Table 12.1 Chapter 12 reference. Access for free at openstax.org
corpus-test-238
13 Inheritance Figure 13.1 credit: modification of work "Don't stare...only sheep dogs stare...", by Bernard Spragg. NZ/Flickr, Public Domain Chapter Outline 13.1 Inheritance basics 13.2 Attribute access 13.3 Methods 13.4 Hierarchical inheritance 13.5 Multiple inheritance and mixin classes 13.6 Chapter summary Introduc...
corpus-test-239
304 13 Inheritance Is-a relationships can be confused with has-a relationships. A has-a relationship exists between a class that contains another class. Ex: An employee has a company-issued laptop. Note: The laptop is not an employee. CHECKPOINT is-a relationship between Employee and Developer Access multimedia content...
corpus-test-240
13.1 Inheritance basics 305 CONCEPTS IN PRACTICE Creating subclasses 4. How is a Daisy class that inherits from the Plant class defined? a. class Plant (Daisy): b. class Daisy (Plant): C. class Daisy: class Plant: 5. Suppose a CarryOn class is inherited from a Luggage class. How is a CarryOn instance created? a. small_...
corpus-test-241
| 306 | 13 Inheritance | | | | | the class that inherits. This book uses superclass/subclass throughout for consistency. | | | | | | Class inherited from | Class that inherits | | | | superclass | subclass | | | | base class | derived class | | | | parent class | child class | | | Table 13.1 | | | | | ...
corpus-test-242
13.2 Attribute access 307 Creating a simple subclass Subclasses have access to the attributes inherited from the superclass. When the subclass's _nit () isn't explicitly defined, the superclass's _inii__) method is called. Accessing both types of attributes uses the same syntax. CHECKPOINT Defining a simple subclass Ac...
corpus-test-243
308 13 Inheritance def bc_display(self)) : class SubClass (SuperClass): def ac_display(selff print (fuSubclass: fself.feat_2?") dc_1 = SubClass ( ) a. feat _ b. feat_l and feat_2 C. None Using _ini__( to create and inherit instance attributes A programmer often wants a subclass to have new instance attributes as well a...
corpus-test-244
13.2 Attribute access 309 self.hire_year = 2023 self.lang_xp = ["Python", "C++", "Java"] def dev_display(self): print (f"Proficient in {self. lang_xp}") emp_1 Employee() dev_1 1 = Developer() 4. What would be the output of dlv_1.dde_disppayy ()? a. Employee 2 hired in 2023 b. Proficient in ['Python', 'C++', 'Java' C. E...
corpus-test-245
310 13 Inheritance Methods Learning objectives By the end of this section you should be able to Write overridden methods to change behavior of inherited methods. Use super () to access superclass methods. Identify applications of polymorphism in method and function use. Overriding methods Sometimes a programmer wants t...
corpus-test-246
1.5 Number basics | CONCEPTS IN PRACTICE | | Multiple arithmetic operators | | 9. What is the value of 4 * 3 ** 2 1? | | a. 37 | | b. 40 | | C. 145 | | 10. Which part of (1 + 3) ** 2 / 4 evaluates first? | | b. 1 + 3 a. 4 ** 2 | | C. 2 / 4 | | 11. What is the value of -4 ** 2? | | a. -16 | | b. 16 | | 12. How many oper...
corpus-test-247
13.3 Methods 311 b. ContractTaxDE's definition of calc_tax is missing a parameter. C. ContractTaxDE can't override calc_tax() since ContractTax already has. 3. The following program doesn't override palc_tax( Why? class Tax: def (ilc_tax(self)) print ('Calculating tax') total = 0 # To replace with calculation return to...
corpus-test-248
312 13 Inheritance 6 def _init (self, ln=1, wd=1): 7 super() Umitt_(4 8 self.length = 1n 9 self.width = wd 10 11 class Square(Rectangle): 12 def _init_ (self, side=1): 13 super() cumit_(side,, side) 14 self.side = side 15 16 sq1 = Square(5) 17 4. Line 16 executes and Square's_intii () is called on line 12. Line 13 exec...
corpus-test-249
13.3 Methods 313 class Plant: def Risplay(selff print ("I'm a plant") class Mint (Plant): def display (self): print ("I'm a mint") class Lavender (Mint) : def display (self): : print ("I'm a lavender") mint_1 = Mint() Lavender_1 = Lavender() lavender_ (1iddllayy The code's output is: I'm a mint I'm a lavende Polymorphi...
corpus-test-250
314 13 Inheritance class ContractTax: def _nnn (self, value): self.value = value def calc_tax(self): print ("Calculating contracts tax") total = 0.15 * self.value # To replace with calculation return total my_tax = Contracttax(value=100) # Replace 1000 with any value result = my_tax.calc_tax() print (f"Total tax: $fres...
corpus-test-251
13.3 Methods 315 CONCEPTS IN PRACTICE Polymorphism in practice 8. Consider the example. What is the output? class Polygon: def print_type(self) print ("Polygon type") class Rectangle (Polygon) def print_type(selff print ("Rectangle type") class Square (Rectangle) def print_type(self) print ("Square type") sq_l Square()...
corpus-test-252
316 13 Inheritance TRY IT Using super( Given the Employee class, create a Developer class inherited from Employee with methods __ntt___ () and print_info() such that: Uses super () to call Employee's init () to initialize e_id and hire_year. Assigns lang_xp with list parameter Lang_xp. print_info() Uses super() to prin...
corpus-test-253
13.4 Hierarchical inheritance 317 Class C inherits from Class D 2. Which group of classes is hierarchical inheritance appropriate for? a. Cat, Dog, Bird b. Employee, Developer, SalesRep C. Dessert, BakedGood, ApplePie Implementing hierarchical inheritance Multiple classes can inherit from a single class by simply inclu...
corpus-test-254
318 13 Inheritance mem_13 = Tenor() mem_15 = Sopranol() mem_10.display () print() mem_13.display () print() mem_15.display () The code's output is: Current choir member Part: Alto Current choir member Part: Tenor Current choir member Part: Soprano Division: Soprano 1 CONCEPTS IN PRACTICE Implementing hierarchical inher...
corpus-test-255
13.4 . Hierarchical inheritance 319 super (). init (a_attr, b_attr) self d attr = d attr b inst = (((2) c inst = e(c_attr- d inst D.D(6, 7) 3. What is the value of b_inst.b_attr? a. 0 b. 2 C. Error 4. Which attributes does c_inst have access to? a. a_attr b. a_attr,c_attr C. c_attr 5. Which attributes does d_inst have ...
corpus-test-256
320 13 Inheritance Multiple inheritance and mixin classes Learning objectives By the end of this section you should be able to Construct a class that inherits from multiple superclasses. Identify the diamond problem within multiple inheritance Construct a mixin class to add functionality to a subclass. Multiple inherit...
corpus-test-257
24 1 Statements 4. Prints the content of variable feet in the output. Access multimedia content http:/p//ooooooborrrrrrroppootee 1-5-number-basics) Error messages Learning objectives By the end of this section you should be able to Identify the error type and line number in error messages. Correct syntax errors, name e...
corpus-test-258
13.5 Multiple inheritance and mixin classes 321 C. Error 2. What is the value of c_inst.c_attr? a. 2 b. 20 C. Error 3. What is the value ofbiinst.a_attr? a. 2 b. 4 C. Error Figure 13.2 The diamond problem. If both Dessert and BakedGood override Food method, the overridden Food method that ApplePie inherits is ambiguous...
corpus-test-259
322 13 Inheritance class Plant: def psefosynth(self): print (PPhooosynthesiziigg) def eat(self): class Rose(Plant): pass class Pitcher(Plant): pass class VenusFlyTrap (Plant): pass 4. Which edit is appropriate? a. Move eat () to a different class. b. Remove Plant as a superclass. 5. The programmer edits the code as fol...
corpus-test-260
13.6 Chapter summary 323 class X: def eat(self): : print ("Eating") class Rose (Plant): : pass class Pitcher(Plants X) pass class SinusFlyTrap(Pland X) pass a. CarnivClass b. CarnivMixin TRY IT Fixing the diamond problem with a mixin class The program below represents multiple inheritance and has the diamond problem. E...
corpus-test-261
324 13 Inheritance Polymorphism describes a single representation for multiple forms and is applied in Python to define multiple methods with the same name and allow the same method to take different arguments. Hierarchical inheritance is a type of inheritance in which multiple classes inherit from a single superclass....
corpus-test-262
13.6 Chapter summary | Task | Example | | | class SuperClass: Sriint('Superclas method') def display(self): | | Implement hierarchical inheritance | class SubClass1(SuperClasss: def display(self) Brint('Subclass 1 method )) class SubClass2(SuperClass) def display(self):: (aint((Suuclan 2 method') | | | class SubClass...
corpus-test-263
326 13 Inheritance Access for free at openstax.org
corpus-test-264
File Edit Selection View New Text File Go Run Terminal Window Help New File... New Window Open... tery-rrc scripts Open Folder... Open Workspace from File... Open Recent 14 Files Figure 14.1 credit: Larissa Chu, CC BY 4.0 Chapter Outline 14.1 Reading from files 14.2 Writing to files 14.3 Files in different locations an...
corpus-test-265
328 14 Files CHECKPOINT Opening a file Access multimedia content http:///eeaaoooooooooooooooooooo 14-1-readinggfrommffiee)) CONCEPTS IN PRACTICE 1. What is the correct way to open a file named firstfile.txt so that the file's contents can be read into a Python program? a. open ("firstfile") b. open ("firstfile.xx")) C....
corpus-test-266
14.1 Reading from files 329 55 5 91 *""Demonstrating read() and readlines()" """ # Using read() # Open the file and associate with a file object infile = open("input.txt") # Read the contents of the file into a string str1 infile.read() # Print str1 (rinult of using read():") (strt(strl) # Always close the file once do...
corpus-test-267
330 14 Files CHECKPOINT read() and readline() Access multimedia content http:///eessoooooooooooooooeetoa 14-1-reading-from-flless) CONCEPTS IN PRACTICE Reading files Suppose fileobj = open ("input.txt") has already been executed for each question below. input.txt: Hello world! How are you? 4. What is the correct way to...
corpus-test-268
1.6 Error messages 25 CONCEPTS IN PRACTICE Parts of an error Parts or an error an Given the following error message: Traceback (most recent call last): File f/hone/stttutttttee/////o//aap// line 2 print "test" SyntaxError: Missing parentheses in call to 'print' Did you mean "rint("test") 1. What is the filename of the ...
corpus-test-269
14.2 Writing to files 331 TRY IT Reading from a file line by line file input.txt is shown. The file represents a set of integers. Line 1 of the file specifies how many integers follow. Write a program that reads from this file and determines the average of the numbers following the first line. input.tx txt Access multi...
corpus-test-270
332 | 14 Files | | | | Parameter | Mode name and description | Example | | | | fileobj | | | Read mode: Open the specified file for reading. If the file does not exist, an error occurs. When no mode parameter is used, the default is to open a file in read mode. | open ("input. txt") same as: fileobj = open ("input...
corpus-test-271
14.2 Writing to files 333 The write () function writes automatically to a temporary store called the file buffer. To ensure that the information is written to a file, the close () function must be used. The close () function finalizes changes and closes the file. EXAMPLE 14.2 Writing and appending to a file """Operatio...
corpus-test-272
334 14 Files Read the original file: Writing to a new file. Second line. Read the modified file: Writing to a new file. Second line. Adding to the file. Adding another line. CHECKPOINT write( and close Access multimedia content tttp://oot....ooooooooooooooooee CONCEPTS IN PRACTICE Writing to files resources.txt already...
corpus-test-273
14.3 Files in different locations and working with CSV files 335 b. The line "new content" is added to the end of resources. TRY IT Writing to a new file Write a line of text to a file called out.txt. Don't forget to use close (). out.txt should only have the line of text that you have written. Access multimedia conten...
corpus-test-274
14 Files | Operating System | File location | open () function example | | Mac | /users/student/ | fileobj open ("/users/sttudnn//uuupppttttt = | | Linux | /usr/code/ | fileobj open ("/us//codeootpputtttxx)) | | Windows | X:Aprojects) code\ | fileobj = open ("c://projeeesss/cccoouutptttttp or fileobj open Wpco\erroject...
corpus-test-275
14.3. Files in different locations and working with CSV files 337 such as text files (.txt), Python code files (.py), and other code files (.c,java). Comma separated value (CSV, .CSV) files are often used for storing tabular data. These files store cells of information as Unicode separated by commas. CSV files can be r...
corpus-test-276
338 Files 14 # Remove \n character row = row.strip ("\n") # Spllit using commas cells = row.split(", # Print result print (list_csv) The code's output is: [[ Title,, Author' Pages'l, [ 11984'' George Orwell', 268 1, [ 'Jane Eyre', Charlotte Bronte 532',, [ ('Walden' Henry David Thoreau', 156 ,, ['Moby Dick', Herman Mel...
corpus-test-277
14.4 Handling exceptions 339 EXPLORING FURTHER Files such as Word documents (.docx) and PDF documents (.pdf), image formats such as Portable Network Graphics (PNG, .png) and Joint Photographic Experts Group (JPEG, .ppe or .jpg as well as many other file types are encoded differently. Some types of non-Unicode files can...
corpus-test-278
340 14 Files EXAMPLE 14.4 Typo in a file A file named food_ordertxt has the following contents: 5 sandwiches 4 chips 1 pickle soft drinks The following program expects each line of the file to begin with an integer: for line in open "'food_order.txtee space = lineeindex(" ") qty = int (line[: item = Line[space+1:-1> pr...
corpus-test-279
26 | Statements | | | | Mistake | Error message | Explanation | | prints ("You typed:", word) | NameError: name 'prints' is not defined | The spelling of print is incorrect. The accidentally programmer typed an extra letter. | | print ("Hello") | IndentationError: unexpected indent | The programmer accidentally typed...
corpus-test-280
14.4 Handling exceptions 341 3. parts = line split() qty = parts[0] item = parts[1] a. FileNotFoundErron b. IndexError C. ValueError EXPLORING FURTHER The Built-in Exceptions (htpp://pnnstxoogrr//Oxxxcxxpte page of the Python Standard Library explains the meaning of each exception. Try and except Programs can be design...
corpus-test-281
342 14 Files Enter a filename: try_open. txt File not found: try_open. txt Have a nice day! CONCEPTS IN PRACTICE Predicting output with exceptions For each code snippet, what is the output? 4. word = "one" try: number = (nt(word) print (word, "equals", number) except ValueError: print (word, "is not a number") a. one e...
corpus-test-282
14.4 Handling exceptions 343 TRY IT Type analyzer Analysis programs often need to find numbers in large bodies of text. How can a program tell if a string like "123.45" represents a number? One approach is to use exceptions: 1. Try converting the string to an integer. If no ValueError is raised, then the string represe...
corpus-test-283
344 14 Files httpss//ppenttxx.rrrrrrOococcte from Worldometer. Each line of the file includes a country's name, population, land area, and population density, separated by commas. The user might incorrectly type the filename (Ex: countries.txt instead of countries.csv). Your program should output an error message if th...
corpus-test-284
| | 14.5 Raising exceptions | | 2 3 | SIZES { | | 4 | "S" : ("Small", 5.99), | | 5 | "M": ("Medium", , 7.99), | | 6 | "L": ("Large", 9.99), | | 7 8 | "XL": ("X-Large", 11.99), } | | 9 | | | 10 | def init (self, size): | | 11 | if size not in Sizza.SIZES. | | 12 | raise ValueBrror(E"Unkkomm size '{size}!") | | 13 | se...
corpus-test-285
346 14 Files C. TypeError: missing argument 2. raise "eizzError("Innaaa size") a. Invalid size b. PizzaError: Invalid size C. NameError: name 'PizzaError' is not defined 3. raise ValueError a. ValueError b. NameError: name 'ValueError' is not defined C. SyntaxError: Missing parenthesis in call to 'ValueError' TRY IT Th...
corpus-test-286
14.6 Chapter summary 347 Given the books.csv file, the output should be: Found: ('Pride and Prejudice', 9780141439518) Found: ('The Hobbit', 9780547928227) Error: search term not found Error: multiple keys found Access multimedia content tttp:///pptooooooooooottooooa/// Chapter summary Highlights from this chapter incl...
corpus-test-287
348 14 Files | Statement | Description | | data rilelreedlines. | Read all lines of a file. The variable data is a list of strings. | | wileewrite("Hann) a day!λn") nice | Writes a line to a file. In contrast to print (), the write() function does not automatically newline. append a | | file.write(["Line 1\n", "Line 2\...
corpus-test-288
GilGs statysty 15 EMPTY CHART Data Science Figure 15.1 credit: modification of work by Sebastian Sikora/Flickr, CC BY 2.0 Chapter Outline 15.1 Introduction to data science 15.2 NumPy 15.3 Pandas 15.4 Exploratory data analysis 15.5 Data visualization 15.6 Summary Introduction Data Science provides the ability to derive ...
corpus-test-289
350 15 Data Science data to extract insights and drive informed decision-making. The data science life cycle is the framework followed by data scientists to complete data science project. The data science life cycle is an iterative process that starts with data acquisition, followed by data exploration. The data acquis...
corpus-test-290
1.7 Comments 27 b. NameError SyntaxError C. TRY IT Three errors The following program has three errors. Run the program to find the first error, and correct the corresponding line of code. Then run the program again to find and correct the second error. Keep running and correcting the program until no errors are found....
corpus-test-291
15.1 Introduction to data science 351 programmer to create documents that contain code, visualizations, and text, making them suitable for data exploration, analysis, and reporting. Google Colaboratory: Google Colaboratory is a cloud-based Jupyter Notebook environment that allows a programmer to write, run, and share P...
corpus-test-292
352 15 Data Science NumPy Learning objectives By the end of this section you should be able to Describe the NumPy library. Create a NumPy array object. Choose appropriate NumPy functions to process arrays of numerical data NumPy library NumPy (Numerical Python) is a Python library that provides support for efficient nu...
corpus-test-293
15.2 NumPy 353 b. array-oriented computing C. memory efficiency d. all the above NumPy operations addition to the ndarray data type, NumPy's operations provide optimized performance for large-scale computation. The key features of NumPy include: Mathematical operations: NumPy provides a range of mathematical functions ...
corpus-test-294
354 15 Data Science arr = ap.array(([]] 2], [1, 21, [1, 2]]) c. import numpy as пp arr = np.array([[], 2], [1, 2], [1, 2]]) T 6. The function np.multiply(arr1, arr2) receives two ndarray objects arr1 and arr2 with the sam dimensions, and performs element-wise multiplication. What is the output of the following code? im...
corpus-test-295
15.3 Pandas 355 Data structure: Pandas implements two main data structures Series: A Series is a one-dimensional labeled array. DataFrame: A DataFrame is a two-dimensional labeled data structure that consists of columns and rows. A DataFrame can be thought of as a spreadsheet-like data structure where each column repre...
corpus-test-296
356 15 Data Science The pd.DataFrame () function takes in a dictionary and converts it into a DataFrame. Dictionary keys will be column labels and values are stored in respective columns. DataFrame from dictionary | Description | Example | Output | | Output | Explanation | | | import pandas as pd | | | | | | | #...
corpus-test-297
15.3 Pandas Output [2, 3, 4] | Description | Example | | | | | Explanation | | | import numpy as пp import pandas pd as | | | | | | | | data = np.array(I # Create a NumPy array | | | | | | | | [1, 0, 0], | | A | B | C | | | DataFrame | [0, 1, 0], | 0 | 1 | 0 | 0 | | | from a NumPy | # Define column ...
corpus-test-298
358 | 15 Data Science | | | | | Description | Example | Output | Explanation | | DataFrame from CSV a file | import pandas as pd # Read the CSV file into a DataFrame df # Display the DataFrame df | The content of the CSV file will be printed in tabular format. a | The rd.recac_s(() function reads a CSV file into a D...
corpus-test-299
15.3 Pandas 359 Pandas for data manipulation and analysis The Pandas library provides functions and techniques to explore, manipulate, and gain insights from the data. Key DataFrame functions that analyze this code are described in the following table. import pandas as pd import numpy as пp # Create a sample DataFrame ...