id
int64
0
25.6k
text
stringlengths
0
4.59k
200
report range specific to the kind of car it' associated with alternativelywe could maintain the association of the get_range(method with the battery but pass it parameter such as car_model the get_range(method would then report range based on the battery size and car model this brings you to an interesting point in you...
201
as you add more functionality to your classesyour files can get longeven when you use inheritance properly in keeping with the overall philosophy of pythonyou'll want to keep your files as uncluttered as possible to helppython lets you store classes in modules and then import the classes you need into your main program...
202
contents of this module you should write docstring for each module you create now we make separate file called my_car py this file will import the car class and then create an instance from that classmy_car py from car import car my_new_car car('audi'' ' print(my_new_car get_descriptive_name()my_new_car odometer_readin...
203
if self battery_size = range elif self battery_size = range message "this car can go approximately str(rangemessage +miles on full charge print(messageclass electriccar(car)"""models aspects of carspecific to electric vehicles ""def __init__(selfmakemodelyear)""initialize attributes of the parent class then initialize ...
204
with comma once you've imported the necessary classesyou're free to make as many instances of each class as you need in this example we make regular volkswagen beetle at and an electric tesla roadster at volkswagen beetle tesla roadster importing an entire module you can also import an entire module and then access the...
205
where the module is used in the program you'll also avoid the potential naming conflicts that can arise when you import every class in module importing module into module sometimes you'll want to spread out your classes over several modules to keep any one file from growing too large and avoid storing unrelated classes...
206
we then create one regular car and one electric car both kinds of cars are created correctly volkswagen beetle tesla roadster finding your own workflow as you can seepython gives you many options for how to structure code in large project it' important to know all these possibilities so you can determine the best ways ...
207
keep track of the order in which you add key-value pairs if you're creating dictionary and want to keep track of the order in which key-value pairs are addedyou can use the ordereddict class from the collections module instances of the ordereddict class behave almost exactly like dictionaries except they keep track of ...
208
- ordereddict rewritestart with exercise - (page )where you used standard dictionary to represent glossary rewrite the program using the ordereddict class and make sure the order of the output matches the order in which key-value pairs were added to the dictionary - dicethe module random contains functions that generat...
209
wrote in programs with multiple import statementsthis convention makes it easier to see where the different modules used in the program come from summary in this you learned how to write your own classes you learned how to store information in class using attributes and how to write methods that give your classes the b...
210
fi now that you've mastered the basic skills you need to write organized programs that are easy to useit' time to think about making your programs even more relevant and usable in this you'll learn to work with files so your programs can quickly analyze lots of data you'll learn to handle errors so your programs don' c...
211
programs with the skills you'll learn in this you'll make your programs more applicableusableand stable reading from file an incredible amount of data is available in text files text files can contain weather datatraffic datasocioeconomic dataliterary worksand more reading from file is particularly useful in data analy...
212
prevents the close(statement from being executedthe file may never close this may seem trivialbut improperly closed files can cause data to be lost or corrupted and if you call close(too early in your programyou'll find yourself trying to work with closed file ( file you can' access)which leads to more errors it' not a...
213
than the one where your program file is storedyou need to provide file pathwhich tells python to look in specific location on your system because text_files is inside python_workyou could use relative file path to open file from text_files relative file path tells python to look for given location relative to the direc...
214
when you're reading fileyou'll often want to examine each line of the file you might be looking for certain information in the fileor you might want to modify the text in the file in some way for exampleyou might want to read through file of weather data and work with any line that includes the word sunny in the descri...
215
making list of lines from file when you use withthe file object returned by open(is only available inside the with block that contains it if you want to retain access to file' contents outside the with blockyou can store the file' lines in list inside the block and then work with that list you can process parts of the ...
216
pi_string and removes the newline character from each line at we print this string and also show how long the string is the variable pi_string contains the whitespace that was on the left side of the digits in each linebut we can get rid of that by using strip(instead of rstrip()filename 'pi_ _digits txtwith open(filen...
217
for line in linespi_string +line strip(print(pi_string[: "print(len(pi_string)the output shows that we do indeed have string containing pi to , , decimal places python has no inherent limit to how much data you can work withyou can work with as much data as your system' memory can handle note to run this program (and m...
218
- learning pythonopen blank file in your text editor and write few lines summarizing what you've learned about python so far start each line with the phrase in python you can save the file as learning_python txt in the same directory as your exercises from this write program that reads the file and prints what you wrot...
219
you to read and write to the file (' +'if you omit the mode argumentpython opens the file in read-only mode by default the open(function automatically creates the file you're writing to if it doesn' already exist howeverbe careful opening file in write mode (' 'because if the file does existpython will erase the file b...
220
outputjust as you've been doing with terminal-based output appending to file if you want to add content to file instead of writing over existing contentyou can open the file in append mode when you open file in append modepython doesn' erase the file before returning the file object any lines you write to the file will...
221
python uses special objects called exceptions to manage errors that arise during program' execution whenever an error occurs that makes python unsure what to do nextit creates an exception object if you write code that handles the exceptionthe program will continue running if you don' handle the exceptionthe program wi...
222
the code in try block workspython skips over the except block if the code in the try block causes an errorpython looks for an except block whose error matches the one that was raised and runs the code in that block in this examplethe code in the try block produces zerodivisionerrorso python looks for an except block te...
223
users see tracebacks nontechnical users will be confused by themand in malicious settingattackers will learn more than you want them to know from traceback for examplethey'll know the name of your program fileand they'll see part of your code that isn' working properly skilled attacker can sometimes use this informatio...
224
second number first numberq the tryexceptelse block works like thispython attempts to run the code in the try statement the only code that should go in try statement is code that might cause an exception to be raised sometimes you'll have additional code that should run only if the try block was successfulthis code goe...
225
msg "sorrythe file filename does not exist print(msgin this examplethe code in the try block produces filenotfounderrorso python looks for an except block that matches that error python then runs the code in that blockand the result is friendly error message instead of tracebacksorrythe file alice txt does not exist th...
226
count the approximate number of words in the file words contents split( num_words len(wordsw print("the file filename has about str(num_wordswords " moved the file alice txt to the correct directoryso the try block will work this time at we take the string contentswhich now contains the entire text of alice in wonderla...
227
to analyze we do this by storing the names of the files we want to analyze in listand then we call count_words(for each file in the list we'll try to count the words for alice in wonderlandsiddharthamoby dickand little womenwhich are all available in the public domain 've intentionally left siddhartha txt out of the di...
228
pass statement at now when filenotfounderror is raisedthe code in the except block runsbut nothing happens no traceback is producedand there' no output in response to the error that was raised users see the word counts for each file that existsbut they don' see any indication that file was not foundthe file alice txt h...
229
so the user can continue entering numbers even if they make mistake and enter text instead of number - cats and dogsmake two filescats txt and dogs txt store at least three names of cats in the first file and three names of dogs in the second file write program that tries to read these files and print the contents of t...
230
file and load the data from that file the next time the program runs you can also use json to share data between different python programs even betterthe json data format is not specific to pythonso you can share data you store in the json format with people who work in many other programming languages it' useful and p...
231
when we open the filewe open it in read mode because python only needs to read from the file at we use the json load(function to load the information stored in numbers jsonand we store it in the variable numbers finally we print the recovered list of numbers and see that it' the same list created in number_writer py[ t...
232
into the variable username now that we've recovered the usernamewe can welcome them back vwelcome backericwe need to combine these two programs into one file when someone runs remember_me pywe want to retrieve their username from memory if possiblethereforewe'll start with try block that attempts to recover the usernam...
233
oftenyou'll come to point where your code will workbut you'll recognize that you could improve the code by breaking it up into series of functions that have specific jobs this process is called refactoring refactoring makes your code cleanereasier to understandand easier to extend we can refactor remember_me py by movi...
234
"""greet the user by name ""username get_stored_username( if usernameprint("welcome backusername "!"elseusername input("what is your name"filename 'username jsonwith open(filename' 'as f_objjson dump(usernamef_objprint("we'll remember you when you come backusername "!"greet_user(the new function get_stored_username(has...
235
purpose we call greet_user()and that function prints an appropriate messageit either welcomes back an existing user or greets new user it does this by calling get_stored_username()which is responsible only for retrieving stored username if one exists finallygreet_user(calls get_new_username(if necessarywhich is respons...
236
ing your code when you write function or classyou can also write tests for that code testing proves that your code works as it' supposed to in response to all the input types it' designed to receive when you write testsyou can be confident that your code will work correctly as more people begin to use your programs you...
237
to learn about testingwe need code to test here' simple function that takes in first and last nameand returns neatly formatted full namename_ function py def get_formatted_name(firstlast)"""generate neatly formatted full name ""full_name first last return full_name title(the function get_formatted_name(combines the fir...
238
modify get_formatted_name()but that would become tedious fortunatelypython provides an efficient way to automate the testing of function' output if we automate the testing of get_formatted_name()we can always be confident that the function will work when given the kinds of names we've written tests for unit tests and t...
239
test and to use the word test in the class name this class must inherit from the class unittest testcase so python knows how to run the tests you write namestestcase contains single method that tests one aspect of get_formatted_name(we call this method test_first_last_name(because we're verifying that names with only f...
240
argumentname_ function py def get_formatted_name(firstmiddlelast)"""generate neatly formatted full name ""full_name first middle last return full_name title(this version should work for people with middle namesbut when we test itwe see that we've broken the function for people with just first and last name this timerun...
241
examine the changes you just made to the functionand figure out how those changes broke the desired behavior in this case get_formatted_name(used to require only two parametersa first name and last name now it requires first namemiddle nameand last name the addition of that mandatory middle name parameter broke the des...
242
now that we know get_formatted_name(works for simple names againlet' write second test for people who include middle name we do this by adding another method to the class namestestcaseimport unittest from name_function import get_formatted_name class namestestcase(unittest testcase)"""tests for 'name_function py""def t...
243
- citycountrywrite function that accepts two parametersa city name and country name the function should return single string of the form citycountrysuch as santiagochile store the function in module called city _functions py create file called test_cities py that tests the function you just wrote (remember that you nee...
244
testcaseso let' look at how we can use one of these methods in the context of testing an actual class table - assert methods available from the unittest module method use assertequal(abverify that = assertnotequal(abverify that ! asserttrue(xverify that is true assertfalse(xverify that is false assertin(itemlistverify ...
245
response using store_response()and show results with show_results(to show that the anonymoussurvey class workslet' write program that uses the classlanguage_ survey py from survey import anonymoussurvey define questionand make survey question "what language did you first learn to speak?my_survey anonymoussurvey(questio...
246
improve anonymoussurvey and the module it' insurvey we could allow each user to enter more than one response we could write method to list only unique responses and to report how many times each response was given we could write another class to manage nonanonymous surveys implementing such changes would risk affecting...
247
ran test in ok this is goodbut survey is useful only if it generates more than one response let' verify that three responses can be stored correctly to do thiswe add another method to testanonymoussurveyimport unittest from survey import anonymoussurvey class testanonymoussurvey(unittest testcase)"""tests for the class...
248
in test_survey py we created new instance of anonymoussurvey in each test methodand we created new responses in each method the unittest testcase class has setup(method that allows you to create these objects once and then use them in each of your test methods when you include setup(method in testcase classpython runs ...
249
ability to store single response or series of individual responses when you're testing your own classesthe setup(method can make your test methods easier to write you make one set of instances and attributes in setup(and then use these instances in all your test methods this is much easier than making new set of instan...
250
be more willing to work with you on projects if you want to contribute to project that other programmers are working onyou'll be expected to show that your code passes existing tests and you'll usually be expected to write tests for new behavior you introduce to the project play around with tests to become familiar wit...
251
projects congratulationsyou now know enough about python to start building interactive and meaningful projects creating your own projects will teach you new skills and solidify your understanding of the concepts introduced in part part ii contains three types of projectsand you can choose to do any or all of these proj...
252
data learning to make visualizations allows you to explore the field of data miningwhich is highly sought-after skill in the world today web applications in the web applications project and )you'll use the django package to create simple web application that allows users to keep journal about any number of topics they'...
253
alien inva sion
254
ip fi let' build gamewe'll use pygamea collection of funpowerful python modules that manage graphicsanimationand even soundmaking it easier for you to build sophisticated games with pygame handling tasks like drawing images to the screenyou can skip much of the tediousdifficult coding and focus on the higher-level logi...
255
it' deeply satisfying to watch others play game you wroteand writing simple game will help you understand how professional games are written as you work through this enter and run the code to understand how each block of code contributes to overall gameplay experiment with different values and settings to gain better u...
256
instructions for installing pip on all systems are included in the sections that follow because you'll need pip for the data visualization and web application projects these instructions are also included in the online resources at com/pythoncrashcourseif you have trouble with the instructions heresee if the online ins...
257
pipnext installing pip to install pipgo to prompted to do so if the code for get-pip py appears in your browsercopy and paste the program into your text editor and save the file as get-pip py once get-pip py is saved on your computeryou'll need to run it with administrative privileges because pip will be installing new...
258
python import pygame if no output appearspython has imported pygame and you're ready to move on to "starting the game projecton page if you're running python two steps are requiredinstalling the libraries pygame depends onand downloading and installing pygame enter the following to install the libraries pygame needs (i...
259
see output scroll by as each library is installed if you also want to enable more advanced functionalitysuch as including sound in gamesyou can install two additional librariesbrew install sdl_mixer portmidi use the following command to install pygame (use pip rather than pip if you're running python )pip install --use...
260
firstwe'll create an empty pygame window here' the basic structure of game written in pygamealien_ invasion py import sys import pygame def run_game()initialize game and create screen object pygame init( screen pygame display set_mode(( )pygame display set_caption("alien invasion" start the main loop for the game while...
261
method any keyboard or mouse event will cause the for loop to run inside the loopwe'll write series of if statements to detect and respond to specific events for examplewhen the player clicks the game window' close buttona pygame quit event is detected and we call sys exit(to exit the game the call to pygame display fl...
262
methodwhich takes only one argumenta color creating settings class each time we introduce new functionality into our gamewe'll typically introduce some new settings as well instead of adding settings throughout the codelet' write module called settings that contains class called settings to store all the settings in on...
263
instance of settings and store it in ai_settings after making the call to pygame init( when we create screen vwe use the screen_width and screen_height attributes of ai_settingsand then we use ai_settings to access the background color when filling the screen at as well adding the ship image now let' add the ship to ou...
264
after choosing an image for the shipwe need to display it onscreen to use our shipwe'll write module called shipwhich contains the class ship this class will manage most of the behavior of the player' ship ship py import pygame class ship()def __init__(selfscreen)"""initialize the ship and set its starting position ""s...
265
increase as you go down and to the right on by screenthe origin is at the top-left cornerand the bottom-right corner has the coordinates ( note we'll position the ship at the bottom center of the screen to do sofirst store the screen' rect in self screen_rect wand then make the value of self rect centerx (the -coordina...
266
refactoringthe game_functions module in larger projectsyou'll often refactor code you've written before adding more code refactoring simplifies the structure of the code you've already writtenmaking it easier to build on in this section we'll create new module called game_functionswhich will store number of functions t...
267
copied from the event loop in alien_invasion py now let' modify alien_invasion py so it imports the game_functions moduleand we'll replace the event loop with call to check_events()alien_ invasion py import pygame from settings import settings from ship import ship import game_functions as gf def run_game()--snip-start...
268
gf check_events(gf update_screen(ai_settingsscreenshiprun_game(these two functions make the while loop simpler and will make further development easier instead of working inside run_game()we can do most of our work in the module game_functions because we wanted to start out working with code in single filewe didn' intr...
269
move the ship to the rightgame_ functions py def check_events(ship)"""respond to keypresses and mouse events ""for event in pygame event get()if event type =pygame quitsys exit( elif event type =pygame keydownif event key =pygame k_rightmove the ship to the right ship rect centerx + we give the check_events(function sh...
270
ship py class ship()def __init__(selfscreen)--snip-start each new ship at the bottom center of the screen self rect centerx self screen_rect centerx self rect bottom self screen_rect bottom movement flag self moving_right false def update(self)"""update the ship' position based on the movement flag ""if self moving_rig...
271
events and before we update the screen this allows the ship' position to be updated in response to player input and ensures the updated position is used when drawing the ship to the screen when you run alien_invasion py and hold down the right arrow keythe ship should move continuously to the right until you release th...
272
keyup event occurs for the k_left keywe set moving_left to false we can use elif blocks here because each event is connected to only one key if the player presses both keys at oncetwo separate events will be detected if you run alien_invasion py nowyou should be able to move the ship continuously to the right and left ...
273
def update(self)"""update the ship' position based on movement flags ""update the ship' center valuenot the rect if self moving_rightself center +self ai_settings ship_speed_factor if self moving_leftself center -self ai_settings ship_speed_factor update rect object from self center self rect centerx self center def bl...
274
at this point the ship will disappear off either edge of the screen if you hold down an arrow key long enough let' correct this so the ship stops moving when it reaches the edge of the screen we do this by modifying the update(method in shipship py def update(self)"""update the ship' position based on movement flags ""...
275
"""respond to keypresses and mouse events ""for event in pygame event get()if event type =pygame quitsys exit(elif event type =pygame keydowncheck_keydown_events(eventshipelif event type =pygame keyupcheck_keyup_events(eventshipwe make two new functionscheck_keydown_events(and check_keyup_ events(each needs an event pa...
276
the ship the game_functions module also contains update_screen()which redraws the screen on each pass through the main loop ship py the ship py file contains the ship class ship has an __init__(methodan update(method to manage the ship' positionand blitme(method to draw the ship to the screen the actual image of the sh...
277
now create bullet py file to store our bullet class here' the first part of bullet pybullet py import pygame from pygame sprite import sprite class bullet(sprite)""" class to manage bullets fired from the ship""def __init__(selfai_settingsscreenship)"""create bullet object at the ship' current position ""super(bulletse...
278
bullet py def update(self)"""move the bullet up the screen ""update the decimal position of the bullet self -self speed_factor update the rect position self rect self def draw_bullet(self)"""draw the bullet to the screen ""pygame draw rect(self screenself colorself rectu the update(method manages the bullet' position w...
279
bullets update(gf update_screen(ai_settingsscreenshipbulletsrun_game(we import group from pygame sprite at uwe make an instance of group and call it bullets this group is created outside of the while loop so we don' create new group of bullets each time the loop cycles note if you make group like this inside the loopyo...
280
--snip-the group bullets is passed to check_keydown_events( when the player presses the spacebarwe create new bullet ( bullet instance that we name new_bulletand add it to the group bullets using the add(methodthe code bullets add(new_bulletstores the new bullet in the group bullets we need to add bullets as parameter ...
281
doing so much unnecessary work to do thiswe need to detect when the bottom value of bullet' rect has value of which indicates the bullet has passed off the top of the screenalien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenshipbulletsship update(bullets update( get rid of bu...
282
in game_functions py to check how many bullets exist before creating new bullet in check_keydown_events()game_ functions py def check_keydown_events(eventai_settingsscreenshipbullets)--snip-elif event key =pygame k_spacecreate new bullet and add it to the bullets group if len(bulletsai_settings bullets_allowednew_bulle...
283
let' move the code for firing bullet to separate function so we can use single line of code to fire bullet and keep the elif block in check_keydown_events(simplegame_ functions py def check_keydown_events(eventai_settingsscreenshipbullets)"""respond to keypresses ""--snip-elif event key =pygame k_spacefire_bullet(ai_se...
284
aliensin this we'll add aliens to alien invasion firstwe'll add one alien near the top of the screenand then we'll generate whole fleet of aliens we'll make the fleet advance sideways and downand we'll get rid of any aliens hit by bullet finallywe'll limit the number of ships player has and end the game when the player...
285
when you're beginning new phase of development on larger projectit' always good idea to revisit your plan and clarify what you want to accomplish with the code you're about to write in this we willexamine our code and determine if we need to refactor before implementing new features add single alien to the top-left cor...
286
the image file you choose in the images folder figure - the alien we'll use to build the fleet creating the alien class now we'll write the alien classalien py import pygame from pygame sprite import sprite class alien(sprite)""" class to represent single alien in the fleet ""def __init__(selfai_settingsscreen)"""initi...
287
alien we initially place each alien near the top-left corner of the screenadding space to the left of it that' equal to the alien' width and space above it equal to its height creating an instance of the alien now we create an instance of alien in alien_invasion pyalien_ invasion py --snip-from ship import ship from al...
288
drawnso the aliens will be the top layer of the screen figure - shows the first alien on the screen figure - the first alien appears now that the first alien appears correctlywe'll write the code to draw an entire fleet building the alien fleet to draw fleetwe need to figure out how many aliens can fit across the scree...
289
width the space needed to display one alien is twice its widthone width for the alien and one width for the empty space to its right to find the number of aliens that fit across the screenwe divide the available space by two times the width of an aliennumber_aliens_x available_space_x ( alien_widthwe'll include these c...
290
game_ functions py def update_screen(ai_settingsscreenshipaliensbullets)--snip-ship blitme(aliens draw(screenmake the most recently drawn screen visible pygame display flip(when you call draw(on grouppygame automatically draws each element in the group at the position defined by its rect attribute in this casealiens dr...
291
rounding down (this is helpful because we' rather have little extra space in each row than an overly crowded row nextset up loop that counts from to the number of aliens we need to make in the main body of the loopcreate new alien and then set its -coordinate value to place it in the row each alien is pushed to the rig...
292
if we were finished creating fleetwe' probably leave create_fleet(as isbut we have more work to doso let' clean up the function bit here' create_fleet(with two new functionsget_number_aliens_x(and create_alien()game_ def get_number_aliens_x(ai_settingsalien_width)functions py """determine the number of aliens that fit ...
293
has some time to start shooting aliens at the beginning of each level each row needs some empty space below itwhich we'll make equal to the height of one alien to find the number of rowswe divide the available space by two times the height of an alien (againif these calculations are offwe'll see it right away and adjus...
294
to repeat (most text editors make it easy to indent and unindent blocks of codebut for help see appendix now when we call create_alien()we include an argument for the row number so each row can be placed farther down the screen the definition of create_alien(needs parameter to hold the row number within create_alien()w...
295
- starsfind an image of star make grid of stars appear on the screen - better starsyou can make more realistic star pattern by introducing randomness when you place each star recall that you can get random number like thisfrom random import randint random_number randint(- , this code returns random integer between - an...
296
now we need to update the position of each alien as wellalien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenshipbulletsship update(gf update_bullets(bulletsgf update_aliens(aliensgf update_screen(ai_settingsscreenshipaliensbulletswe update the alienspositions after the bullets...
297
now we need method to check whether an alien is at either edgeand we need to modify update(to allow each alien to move in the appropriate directionalien py def check_edges(self)"""return true if alien is at edge of screen ""screen_rect self screen get_rect(if self rect right >screen_rect rightreturn true elif self rect...
298
"""drop the entire fleet and change the fleet' direction ""for alien in aliens sprites() alien rect +ai_settings fleet_drop_speed ai_settings fleet_direction *- def update_aliens(ai_settingsaliens)""check if the fleet is at an edgeand then update the postions of all aliens in the fleet "" check_fleet_edges(ai_settingsa...
299
we've built our ship and fleet of aliensbut when the bullets reach the aliensthey simply pass through because we aren' checking for collisions in game programmingcollisions happen when game elements overlap to make the bullets shoot down alienswe'll use the method sprite groupcollide(to look for collisions between memb...