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 your growth as programmer when you wrestle with questions like theseyou're thinking at higher logical level rather than syntax-focused level you're thinking not about pythonbut about how to represent the real world in code when you reach this pointyou'll realize there are often no right or wrong approaches to modeling real-world situations some approaches are more efficient than othersbut it takes practice to find the most efficient representations if your code is working as you want it toyou're doing welldon' be discouraged if you find you're ripping apart your classes and rewriting them several times using different approaches in the quest to write accurateefficient codeeveryone goes through this process try it yourse lf - ice cream standan ice cream stand is specific kind of restaurant write class called icecreamstand that inherits from the restaurant class you wrote in exercise - (page or exercise - (page either version of the class will workjust pick the one you like better add an attribute called flavors that stores list of ice cream flavors write method that displays these flavors create an instance of icecreamstandand call this method - adminan administrator is special kind of user write class called admin that inherits from the user class you wrote in exercise - (page or exercise - (page add an attributeprivilegesthat stores list of strings like "can add post""can delete post""can ban user"and so on write method called show_privileges(that lists the administrator' set of privileges create an instance of adminand call your method - privilegeswrite separate privileges class the class should have one attributeprivilegesthat stores list of strings as described in exercise - move the show_privileges(method to this class make privileges instance as an attribute in the admin class create new instance of admin and use your method to show its privileges - battery upgradeuse the final version of electric_car py from this section add method to the battery class called upgrade_battery(this method should check the battery size and set the capacity to if it isn' already make an electric car with default battery sizecall get_range(onceand then call get_range( second time after upgrading the battery you should see an increase in the car' range
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 importing single class let' create module containing just the car class this brings up subtle naming issuewe already have file named car py in this but this module should be named car py because it contains code representing car we'll resolve this naming issue by storing the car class in module named car pyreplacing the car py file we were previously using from now onany program that uses this module will need more specific filenamesuch as my_car py here' car py with just the code from the class carcar py """ class that can be used to represent car ""class car()""" simple attempt to represent car ""def __init__(selfmakemodelyear)"""initialize attributes to describe car ""self make make self model model self year year self odometer_reading def get_descriptive_name(self)"""return neatly formatted descriptive name ""long_name str(self yearself make self model return long_name title(def read_odometer(self)"""print statement showing the car' mileage ""print("this car has str(self odometer_readingmiles on it "def update_odometer(selfmileage)""set the odometer reading to the given value reject the change if it attempts to roll the odometer back ""if mileage >self odometer_readingself odometer_reading mileage elseprint("you can' roll back an odometer!"def increment_odometer(selfmiles)"""add the given amount to the odometer reading ""self odometer_reading +miles classes
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_reading my_new_car read_odometer(the import statement at tells python to open the car module and import the class car now we can use the car class as if it were defined in this file the output is the same as we saw earlier audi this car has miles on it importing classes is an effective way to program picture how long this program file would be if the entire car class were included when you instead move the class to module and import the moduleyou still get all the same functionalitybut you keep your main program file clean and easy to read you also store most of the logic in separate filesonce your classes work as you want them toyou can leave those files alone and focus on the higher-level logic of your main program storing multiple classes in module you can store as many classes as you need in single modulealthough each class in module should be related somehow the classes battery and electriccar both help represent carsso let' add them to the module car pycar py """ set of classes used to represent gas and electric cars ""class car()--snip-class battery()""" simple attempt to model battery for an electric car ""def __init__(selfbattery_size= )"""initialize the batteery' attributes ""self battery_size battery_size def describe_battery(self)"""print statement describing the battery size ""print("this car has str(self battery_size"-kwh battery "def get_range(self)
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 attributes specific to an electric car ""super(__init__(makemodelyearself battery battery(now we can make new file called my_electric_car pyimport the electriccar classand make an electric carmy_electric_ car py from car import electriccar my_tesla electriccar('tesla''model ' print(my_tesla get_descriptive_name()my_tesla battery describe_battery(my_tesla battery get_range(this has the same output we saw earliereven though most of the logic is hidden away in module tesla model this car has -kwh battery this car can go approximately miles on full charge importing multiple classes from module you can import as many classes as you need into program file if we want to make regular car and an electric car in the same filewe need to import both classescar and electriccarmy_cars py from car import carelectriccar my_beetle car('volkswagen''beetle' print(my_beetle get_descriptive_name() my_tesla electriccar('tesla''roadster' print(my_tesla get_descriptive_name()classes
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 classes you need using dot notation this approach is simple and results in code that is easy to read because every call that creates an instance of class includes the module nameyou won' have naming conflicts with any names used in the current file here' what it looks like to import the entire car module and then create regular car and an electric carmy_cars py import car my_beetle car car('volkswagen''beetle' print(my_beetle get_descriptive_name() my_tesla car electriccar('tesla''roadster' print(my_tesla get_descriptive_name()at we import the entire car module we then access the classes we need through the module_name class_name syntax at we again create volkswagen beetleand at we create tesla roadster importing all classes from module you can import every class from module using the following syntaxfrom module_name import this method is not recommended for two reasons firstit' helpful to be able to read the import statements at the top of file and get clear sense of which classes program uses with this approach it' unclear which classes you're using from the module this approach can also lead to confusion with names in the file if you accidentally import class with the same name as something else in your program fileyou can create errors that are hard to diagnose show this here because even though it' not recommended approachyou're likely to see it in other people' code if you need to import many classes from moduleyou're better off importing the entire module and using the module_name class_name syntax
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 in the same module when you store your classes in several modulesyou may find that class in one module depends on class in another module when this happensyou can import the required class into the first module for examplelet' store the car class in one module and the electriccar and battery classes in separate module we'll make new module called electric_car py--replacing the electric_car py file we created earlier--and copy just the battery and electriccar classes into this fileelectric_car py """ set of classes that can be used to represent electric cars "" from car import car class battery()--snip-class electriccar(car)--snip-the class electriccar needs access to its parent class carso we import car directly into the module at if we forget this linepython will raise an error when we try to make an electriccar instance we also need to update the car module so it contains only the car classcar py """ class that can be used to represent car ""class car()--snip-now we can import from each module separately and create whatever kind of car we needmy_cars py from car import car from electric_car import electriccar my_beetle car('volkswagen''beetle' print(my_beetle get_descriptive_name()my_tesla electriccar('tesla''roadster' print(my_tesla get_descriptive_name()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 to organize your projects as well as understand other people' projects when you're starting outkeep your code structure simple try doing everything in one file and moving your classes to separate modules once everything is working if you like how modules and files interacttry storing your classes in modules when you start project find an approach that lets you write code that worksand go from there try it yourse lf - imported restaurantusing your latest restaurant classstore it in module make separate file that imports restaurant make restaurant instanceand call one of restaurant' methods to show that the import statement is working properly - imported adminstart with your work from exercise - (page store the classes userprivilegesand admin in one module create separate filemake an admin instanceand call show_privileges(to show that everything is working correctly - multiple modulesstore the user class in one moduleand store the privileges and admin classes in separate module in separate filecreate an admin instance and call show_privileges(to show that everything is still working correctly the python standard library the python standard library is set of modules included with every python installation now that you have basic understanding of how classes workyou can start to use modules like these that other programmers have written you can use any function or class in the standard library by including simple import statement at the top of your file let' look at one classordereddictfrom the module collections
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 the order in which key-value pairs are added let' revisit the favorite_languages py example from this time we'll keep track of the order in which people respond to the pollfavorite_ from collections import ordereddict languages py favorite_languages ordereddict( favorite_languages['jen''pythonfavorite_languages['sarah''cfavorite_languages['edward''rubyfavorite_languages['phil''pythonx for namelanguage in favorite_languages items()print(name title("' favorite language is language title("we begin by importing the ordereddict class from the module collections at at we create an instance of the ordereddict class and store this instance in favorite_languages notice there are no curly bracketsthe call to ordereddict(creates an empty ordered dictionary for us and stores it in favorite_languages we then add each name and language to favorite_languages one at time now when we loop through favorite_languages at xwe know we'll always get responses back in the order they were addedjen' favorite language is python sarah' favorite language is edward' favorite language is ruby phil' favorite language is python this is great class to be aware of because it combines the main benefit of lists (retaining your original orderwith the main feature of dictionaries (connecting pieces of informationas you begin to model real-world situations that you care aboutyou'll probably come across situation where an ordered dictionary is exactly what you need as you learn more about the standard libraryyou'll become familiar with number of modules like this that help you handle common situations note you can also download modules from external sources you'll see number of these examples in part iiwhere we'll need external modules to complete each project classes
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 generate random numbers in variety of ways the function randint(returns an integer in the range you provide the following code returns number between and from random import randint randint( make class die with one attribute called sideswhich has default value of write method called roll_die(that prints random number between and the number of sides the die has make -sided die and roll it times make -sided die and -sided die roll each die times - python module of the weekone excellent resource for exploring the python standard library is site called python module of the week go to looks interesting to you and read about itor explore the documentation of the collections and random modules styling classes few styling issues related to classes are worth clarifyingespecially as your programs become more complicated class names should be written in camelcaps to do thiscapitalize the first letter of each word in the nameand don' use underscores instance and module names should be written in lowercase with underscores between words every class should have docstring immediately following the class definition the docstring should be brief description of what the class doesand you should follow the same formatting conventions you used for writing docstrings in functions each module should also have docstring describing what the classes in module can be used for you can use blank lines to organize codebut don' use them excessively within class you can use one blank line between methodsand within module you can use two blank lines to separate classes if you need to import module from the standard library and module that you wroteplace the import statement for the standard library module
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 behavior they need you learned to write __init__(methods that create instances from your classes with exactly the attributes you want you saw how to modify the attributes of an instance directly and through methods you learned that inheritance can simplify the creation of classes that are related to each otherand you learned to use instances of one class as attributes in another class to keep each class simple you saw how storing classes in modules and importing classes you need into the files where they'll be used can keep your projects organized you started learning about the python standard libraryand you saw an example based on the ordereddict class from the collections module finallyyou learned to style your classes using python conventions in you'll learn to work with files so you can save the work you've done in program and the work you've allowed users to do you'll also learn about exceptionsa special python class designed to help you respond to errors when they arise classes
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' crash when they encounter unexpected situations you'll learn about exceptionswhich are special objects python creates to manage errors that arise while program is running you'll also learn about the json modulewhich allows you to save user data so it isn' lost when your program stops running learning to work with files and save data will make your programs easier for people to use users will be able to choose what data to enter and when to enter it people can run your programdo some workand then close the program and pick up where they left off later learning to handle exceptions will help you deal with situations in which files don' exist and deal with other problems that can cause your programs to crash this will make your programs more robust when they encounter bad datawhether
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 analysis applicationsbut it' also applicable to any situation in which you want to analyze or modify information stored in file for exampleyou can write program that reads in the contents of text file and rewrites the file with formatting that allows browser to display it when you want to work with the information in text filethe first step is to read the file into memory you can read the entire contents of fileor you can work through the file one line at time reading an entire file to beginwe need file with few lines of text in it let' start with file that contains pi to decimal places with decimal places per linepi_digits txt to try the following examples yourselfyou can enter these lines in an editor and save the file as pi_digits txtor you can download the file from the book' resources through the file in the same directory where you'll store this programs here' program that opens this filereads itand prints the contents of the file to the screenfile_reader py with open('pi_digits txt'as file_objectcontents file_object read(print(contentsthe first line of this program has lot going on let' start by looking at the open(function to do any work with fileeven just printing its contentsyou first need to open the file to access it the open(function needs one argumentthe name of the file you want to open python looks for this file in the directory where the program that' currently being executed is stored in this examplefile_reader py is currently runningso python looks for pi_digits txt in the directory where file_reader py is stored the open(function returns an object representing the file hereopen('pi_digits txt'returns an object representing pi_digits txt python stores this object in file_objectwhich we'll work with later in the program the keyword with closes the file once access to it is no longer needed notice how we call open(in this program but not close(you could open
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 always easy to know exactly when you should close filebut with the structure shown herepython will figure that out for you all you have to do is open the file and work with it as desiredtrusting that python will close it automatically when the time is right once we have file object representing pi_digits txtwe use the read(method in the second line of our program to read the entire contents of the file and store it as one long string in contents when we print the value of contentswe get the entire text file back the only difference between this output and the original file is the extra blank line at the end of the output the blank line appears because read(returns an empty string when it reaches the end of the filethis empty string shows up as blank line if you want to remove the extra blank lineyou can use rstrip(in the print statementwith open('pi_digits txt'as file_objectcontents file_object read(print(contents rstrip()recall that python' rstrip(method removesor stripsany whitespace characters from the right side of string now the output matches the contents of the original file exactly file paths when you pass simple filename like pi_digits txt to the open(functionpython looks in the directory where the file that' currently being executed (that isyour py program fileis stored sometimesdepending on how you organize your workthe file you want to open won' be in the same directory as your program file for exampleyou might store your program files in folder called python_workinside python_workyou might have another folder called text_files to distinguish your program files from the text files they're manipulating even though text_files is in python_workjust passing open(the name of file in text_files won' workbecause python will only look in python_work and stop thereit won' go on files and exceptions
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 directory where the currently running program file is stored on linux and os xyou' writewith open('text_files/filename txt'as file_objectthis line tells python to look for the desired txt file in the folder text_files and assumes that text_files is located inside python_work (which it ison windows systemsyou use backslash (\instead of forward slash (/in the file pathwith open('text_files\filename txt'as file_objectyou can also tell python exactly where the file is on your computer regardless of where the program that' being executed is stored this is called an absolute file path you use an absolute path if relative path doesn' work for instanceif you've put text_files in some folder other than python_work--saya folder called other_files--then just passing open(the path 'text_files/filename txtwon' work because python will only look for that location inside python_work you'll need to write out full path to clarify where you want python to look absolute paths are usually longer than relative pathsso it' helpful to store them in variable and then pass that variable to open(on linux and os xabsolute paths look like thisfile_path '/home/ehmatthes/other_files/text_files/filename txtwith open(file_pathas file_objectand on windows they look like thisfile_path ' :\users\ehmatthes\other_files\text_files\filename txtwith open(file_pathas file_objectusing absolute pathsyou can read files from any location on your system for now it' easiest to store files in the same directory as your program files or in folder such as text_files within the directory that stores your program files note windows systems will sometimes interpret forward slashes in file paths correctly if you're using windows and you're not getting the results you expectmake sure you try using backslashes
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 description of that day' weather in news reportyou might look for any line with the tag and rewrite that line with specific kind of formatting you can use for loop on the file object to examine each line from file one at timefile_reader py filename 'pi_digits txtv with open(filenameas file_objectw for line in file_objectprint(lineat we store the name of the file we're reading from in the variable filename this is common convention when working with files because the variable filename doesn' represent the actual file--it' just string telling python where to find the file--you can easily swap out 'pi_digits txtfor the name of another file you want to work with after we call open()an object representing the file and its contents is stored in the variable file_object we again use the with syntax to let python open and close the file properly to examine the file' contentswe work through each line in the file by looping over the file object when we print each linewe find even more blank lines these blank lines appear because an invisible newline character is at the end of each line in the text file the print statement adds its own newline each time we call itso we end up with two newline characters at the end of each lineone from the file and one from the print statement using rstrip(on each line in the print statement eliminates these extra blank linesfilename 'pi_digits txtwith open(filenameas file_objectfor line in file_objectprint(line rstrip()files and exceptions
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 file immediately and postpone some processing for later in the program the following example stores the lines of pi_digits txt in list inside the with block and then prints the lines outside the with blockfilename 'pi_digits txtu with open(filenameas file_objectlines file_object readlines( for line in linesprint(line rstrip()at the readlines(method takes each line from the file and stores it in list this list is then stored in lineswhich we can continue to work with after the with block ends at we use simple for loop to print each line from lines because each item in lines corresponds to each line in the filethe output matches the contents of the file exactly working with file' contents after you've read file into memoryyou can do whatever you want with that dataso let' briefly explore the digits of pi firstwe'll attempt to build single string containing all the digits in the file with no whitespace in itpi_string py filename 'pi_digits txtwith open(filenameas file_objectlines file_object readlines( pi_string ' for line in linespi_string +line rstrip( print(pi_stringprint(len(pi_string)we start by opening the file and storing each line of digits in listjust as we did in the previous example at we create variablepi_stringto
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(filenameas file_objectlines file_object readlines(pi_string 'for line in linespi_string +line strip(print(pi_stringprint(len(pi_string)now we have string containing pi to decimal places the string is characters long because it also includes the leading and decimal point note when python reads from text fileit interprets all text in the file as string if you read in number and want to work with that value in numerical contextyou'll have to convert it to an integer using the int(function or convert it to float using the float(function large filesone million digits so far we've focused on analyzing text file that contains only three linesbut the code in these examples would work just as well on much larger files if we start with text file that contains pi to , , decimal places instead of just we can create single string containing all these digits we don' need to change our program at all except to pass it different file we'll also print just the first decimal placesso we don' have to watch million digits scroll by in the terminalpi_string py filename 'pi_million_digits txtwith open(filenameas file_objectlines file_object readlines(files and exceptions
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 many of the examples that follow)you'll need to download the resources available at is your birthday contained in pii've always been curious to know if my birthday appears anywhere in the digits of pi let' use the program we just wrote to find out if someone' birthday appears anywhere in the first million digits of pi we can do this by expressing each birthday as string of digits and seeing if that string appears anywhere in pi_stringfilename 'pi_million_digits txtwith open(filenameas file_objectlines file_object readlines(pi_string 'for line in linespi_string +line rstrip( birthday input("enter your birthdayin the form mmddyy" if birthday in pi_stringprint("your birthday appears in the first million digits of pi!"elseprint("your birthday does not appear in the first million digits of pi "at we prompt for the user' birthdayand then at we check if that string is in pi_string let' try itenter your birthdatein the form mmddyy your birthday appears in the first million digits of pimy birthday does appear in the digits of pionce you've read from fileyou can analyze its contents in just about any way you can imagine
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 wrote three times print the contents once by reading in the entire fileonce by looping over the file objectand once by storing the lines in list and then working with them outside the with block - learning cyou can use the replace(method to replace any word in string with different word here' quick example showing how to replace 'dogwith 'catin sentencemessage " really like dogs message replace('dog''cat'' really like cats read in each line from the file you just createdlearning_python txtand replace the word python with the name of another languagesuch as print each modified line to the screen writing to file one of the simplest ways to save data is to write it to file when you write text to filethe output will still be available after you close the terminal containing your program' output you can examine output after program finishes runningand you can share the output files with others as well you can also write programs that read the text back into memory and work with it again later writing to an empty file to write text to fileyou need to call open(with second argument telling python that you want to write to the file to see how this workslet' write simple message and store it in file instead of printing it to the screenwrite_ message py filename 'programming txtu with open(filename' 'as file_objectv file_object write(" love programming "the call to open(in this example has two arguments the first argument is still the name of the file we want to open the second argument' 'tells python that we want to open the file in write mode you can open file files and exceptions
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 before returning the file object at we use the write(method on the file object to write string to the file this program has no terminal outputbut if you open the file programming txtyou'll see one lineprogramming txt love programming this file behaves like any other file on your computer you can open itwrite new text in itcopy from itpaste to itand so forth note python can only write strings to text file if you want to store numerical data in text fileyou'll have to convert the data to string format first using the str(function writing multiple lines the write(function doesn' add any newlines to the text you write so if you write more than one line without including newline charactersyour file may not look the way you want it tofilename 'programming txtwith open(filename' 'as file_objectfile_object write(" love programming "file_object write(" love creating new games "if you open programming txtyou'll see the two lines squished togetheri love programming love creating new games including newlines in your write(statements makes each string appear on its own linefilename 'programming txtwith open(filename' 'as file_objectfile_object write(" love programming \ "file_object write(" love creating new games \ "the output now appears on separate linesi love programming love creating new games
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 be added at the end of the file if the file doesn' exist yetpython will create an empty file for you let' modify write_message py by adding some new reasons we love programming to the existing file programming txtwrite_ message py filename 'programming txtu with open(filename' 'as file_objectv file_object write(" also love finding meaning in large datasets \ "file_object write(" love creating apps that can run in browser \ "at we use the 'aargument to open the file for appending rather than writing over the existing file at we write two new lineswhich are added to programming txtprogramming txt love programming love creating new games also love finding meaning in large datasets love creating apps that can run in browser we end up with the original contents of the filefollowed by the new content we just added try it yourse lf - guestwrite program that prompts the user for their name when they respondwrite their name to file called guest txt - guest bookwrite while loop that prompts users for their name when they enter their nameprint greeting to the screen and add line recording their visit in file called guest_book txt make sure each entry appears on new line in the file - programming pollwrite while loop that asks people why they like programming each time someone enters reasonadd their reason to file that stores all the responses files and exceptions
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 will halt and show tracebackwhich includes report of the exception that was raised exceptions are handled with tryexcept blocks tryexcept block asks python to do somethingbut it also tells python what to do if an exception is raised when you use tryexcept blocksyour programs will continue running even if things start to go wrong instead of tracebackswhich can be confusing for users to readusers will see friendly error messages that you write handling the zerodivisionerror exception let' look at simple error that causes python to raise an exception you probably know that it' impossible to divide number by zerobut let' ask python to do it anywaydivision py print( / of course python can' do thisso we get tracebacktraceback (most recent call last)file "division py"line in print( / zerodivisionerrordivision by zero the error reported at in the tracebackzerodivisionerroris an exception object python creates this kind of object in response to situation where it can' do what we ask it to when this happenspython stops the program and tells us the kind of exception that was raised we can use this information to modify our program we'll tell python what to do when this kind of exception occursthat wayif it happens againwe're prepared using try-except blocks when you think an error may occuryou can write tryexcept block to handle the exception that might be raised you tell python to try running some codeand you tell it what to do if the code results in particular kind of exception here' what tryexcept block for handling the zerodivisionerror exception looks liketryprint( / except zerodivisionerrorprint("you can' divide by zero!"
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 telling it how to respond python then runs the code in that blockand the user sees friendly error message instead of tracebackyou can' divide by zeroif more code followed the tryexcept blockthe program would continue running because we told python how to handle the error let' look at an example where catching an error can allow program to continue running using exceptions to prevent crashes handling errors correctly is especially important when the program has more work to do after the error occurs this happens often in programs that prompt users for input if the program responds to invalid input appropriatelyit can prompt for more valid input instead of crashing let' create simple calculator that does only divisiondivision py print("give me two numbersand 'll divide them "print("enter 'qto quit "while truefirst_number input("\nfirst number"if first_number =' 'break second_number input("second number"if second_number =' 'break answer int(first_numberint(second_numberprint(answeru this program prompts the user to input first_number andif the user does not enter to quita second_number we then divide these two numbers to get an answer this program does nothing to handle errorsso asking it to divide by zero causes it to crashgive me two numbersand 'll divide them enter 'qto quit first number second number traceback (most recent call last)file "division py"line in answer int(first_numberint(second_numberzerodivisionerrordivision by zero files and exceptions
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 information to determine which kind of attacks to use against your code the else block we can make this program more error resistant by wrapping the line that might produce errors in tryexcept block the error occurs on the line that performs the divisionso that' where we'll put the tryexcept block this example also includes an else block any code that depends on the try block executing successfully goes in the else blockprint("give me two numbersand 'll divide them "print("enter 'qto quit "while truefirst_number input("\nfirst number"if first_number =' 'break second_number input("second number" tryanswer int(first_numberint(second_numberv except zerodivisionerrorprint("you can' divide by !" elseprint(answerwe ask python to try to complete the division operation in try block uwhich includes only the code that might cause an error any code that depends on the try block succeeding is added to the else block in this case if the division operation is successfulwe use the else block to print the result the except block tells python how to respond when zerodivisionerror arises if the try statement doesn' succeed because of division by zero errorwe print friendly message telling the user how to avoid this kind of error the program continues to runand the user never sees tracebackgive me two numbersand 'll divide them enter 'qto quit first number second number you can' divide by
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 goes in the else block the except block tells python what to do in case certain exception arises when it tries to run the code in the try statement by anticipating likely sources of errorsyou can write robust programs that continue to run even when they encounter invalid data and missing resources your code will be resistant to innocent user mistakes and malicious attacks handling the filenotfounderror exception one common issue when working with files is handling missing files the file you're looking for might be in different locationthe filename may be misspelledor the file may not exist at all you can handle all of these situations in straightforward way with tryexcept block let' try to read file that doesn' exist the following program tries to read in the contents of alice in wonderlandbut haven' saved the file alice txt in the same directory as alice pyalice py filename 'alice txtwith open(filenameas f_objcontents f_obj read(python can' read from missing fileso it raises an exceptiontraceback (most recent call last)file "alice py"line in with open(filenameas f_objfilenotfounderror[errno no such file or directory'alice txtthe last line of the traceback reports filenotfounderrorthis is the exception python creates when it can' find the file it' trying to open in this examplethe open(function produces the errorso to handle itthe try block will begin just before the line that contains open()filename 'alice txttrywith open(filenameas f_objcontents f_obj read(files and exceptions
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 the program has nothing more to do if the file doesn' existso the error-handling code doesn' add much to this program let' build on this example and see how exception handling can help when you're working with more than one file analyzing text you can analyze text files containing entire books many classic works of literature are available as simple text files because they are in the public domain the texts used in this section come from project gutenberg (if you're interested in working with literary texts in your programming projects let' pull in the text of alice in wonderland and try to count the number of words in the text we'll use the string method split()which can build list of words from string here' what split(does with string containing just the title "alice in wonderland"title "alice in wonderlandtitle split(['alice''in''wonderland'the split(method separates string into parts wherever it finds space and stores all the parts of the string in list the result is list of words from the stringalthough some punctuation may also appear with some of the words to count the number of words in alice in wonderlandwe'll use split(on the entire text then we'll count the items in the list to get rough idea of the number of words in the textfilename 'alice txttrywith open(filenameas f_objcontents f_obj read(except filenotfounderrormsg "sorrythe file filename does not exist print(msg
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 wonderland as one long stringand use the split(method to produce list of all the words in the book when we use len(on this list to examine its lengthwe get good approximation of the number of words in the original string at we print statement that reports how many words were found in the file this code is placed in the else block because it will work only if the code in the try block was executed successfully the output tells us how many words are in alice txtthe file alice txt has about words the count is little high because extra information is provided by the publisher in the text file used herebut it' good approximation of the length of alice in wonderland working with multiple files let' add more books to analyze but before we dolet' move the bulk of this program to function called count_words(by doing soit will be easier to run the analysis for multiple booksword_count py def count_words(filename)"""count the approximate number of words in file ""trywith open(filenameas f_objcontents f_obj read(except filenotfounderrormsg "sorrythe file filename does not exist print(msgelsecount approximate number of words in the file words contents split(num_words len(wordsprint("the file filename has about str(num_wordswords "filename 'alice txtcount_words(filenamemost of this code is unchanged we simply indented it and moved it into the body of count_words(it' good habit to keep comments up to date when you're modifying programso we changed the comment to docstring and reworded it slightly files and exceptions
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 directory containing word_count pyso we can see how well our program handles missing filedef count_words(filename)--snip-filenames ['alice txt''siddhartha txt''moby_dick txt''little_women txt'for filename in filenamescount_words(filenamethe missing siddhartha txt file has no effect on the rest of the program' executionthe file alice txt has about words sorrythe file siddhartha txt does not exist the file moby_dick txt has about words the file little_women txt has about words using the tryexcept block in this example provides two significant advantages we prevent our users from seeing tracebackand we let the program continue analyzing the texts it' able to find if we don' catch the filenotfounderror that siddhartha txt raisedthe user would see full tracebackand the program would stop running after trying to analyze siddhartha it would never analyze moby dick or little women failing silently in the previous examplewe informed our users that one of the files was unavailable but you don' need to report every exception you catch sometimes you'll want the program to fail silently when an exception occurs and continue on as if nothing happened to make program fail silentlyyou write try block as usualbut you explicitly tell python to do nothing in the except block python has pass statement that tells it to do nothing in blockdef count_words(filename)"""count the approximate number of words in file ""try--snip-except filenotfounderroru pass else--snip-filenames ['alice txt''siddhartha txt''moby_dick txt''little_women txt'for filename in filenamescount_words(filename
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 has about words the file moby_dick txt has about words the file little_women txt has about words the pass statement also acts as placeholder it' reminder that you're choosing to do nothing at specific point in your program' execution and that you might want to do something there later for examplein this program we might decide to write any missing filenames to file called missing_files txt our users wouldn' see this filebut we' be able to read the file and deal with any missing texts deciding which errors to report how do you know when to report an error to your users and when to fail silentlyif users know which texts are supposed to be analyzedthey might appreciate message informing them why some texts were not analyzed if users expect to see some results but don' know which books are supposed to be analyzedthey might not need to know that some texts were unavailable giving users information they aren' looking for can decrease the usability of your program python' error-handling structures give you finegrained control over how much to share with users when things go wrongit' up to you to decide how much information to share well-writtenproperly tested code is not very prone to internal errorssuch as syntax or logical errors but every time your program depends on something externalsuch as user inputthe existence of fileor the availability of network connectionthere is possibility of an exception being raised little experience will help you know where to include exception handling blocks in your program and how much to report to users about errors that arise try it yourse lf - additionone common problem when prompting for numerical input occurs when people provide text instead of numbers when you try to convert the input to an intyou'll get typeerror write program that prompts for two numbers add them together and print the result catch the typeerror if either input value is not numberand print friendly error message test your program by entering two numbers and then by entering some text instead of number (continuedfiles and exceptions
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 the file to the screen wrap your code in try-except block to catch the filenotfound errorand print friendly message if file is missing move one of the files to different location on your systemand make sure the code in the except block executes properly - silent cats and dogsmodify your except block in exercise - to fail silently if either file is missing - common wordsvisit project gutenberg (and find few texts you' like to analyze download the text files for these worksor copy the raw text from your browser into text file on your computer you can use the count(method to find out how many times word or phrase appears in string for examplethe following code counts the number of times 'rowappears in stringline "rowrowrow your boatline count('row' line lower(count('row' notice that converting the string to lowercase using lower(catches all appearances of the word you're looking forregardless of how it' formatted write program that reads the files you found at project gutenberg and determines how many times the word 'theappears in each text storing data many of your programs will ask users to input certain kinds of information you might allow users to store preferences in game or provide data for visualization whatever the focus of your program isyou'll store the information users provide in data structures such as lists and dictionaries when users close programyou'll almost always want to save the information they entered simple way to do this involves storing your data using the json module
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 portable formatand it' easy to learn note the json (javascript object notationformat was originally developed for javascript howeverit has since become common format used by many languagesincluding python using json dump(and json load(let' write short program that stores set of numbers and another program that reads these numbers back into memory the first program will use json dump(to store the set of numbersand the second program will use json load(the json dump(function takes two argumentsa piece of data to store and file object it can use to store the data here' how you can use json dump(to store list of numbersnumber_ writer py import json numbers [ filename 'numbers jsonv with open(filename' 'as f_objw json dump(numbersf_objwe first import the json module and then create list of numbers to work with at we choose filename in which to store the list of numbers it' customary to use the file extension json to indicate that the data in the file is stored in the json format then we open the file in write modewhich allows json to write the data to the file at we use the json dump(function to store the list numbers in the file numbers json this program has no outputbut let' open the file numbers json and look at it the data is stored in format that looks just like python[ now we'll write program that uses json load(to read the list back into memorynumber_ reader py import json filename 'numbers jsonv with open(filenameas f_objw numbers json load(f_objprint(numbersfiles and exceptions
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[ this is simple way to share data between two programs saving and reading user-generated data saving data with json is useful when you're working with user-generated databecause if you don' store your user' information somehowyou'll lose it when the program stops running let' look at an example where we prompt the user for their name the first time they run program and then remember their name when they run the program again let' start by storing the user' nameremember_ me py import json username input("what is your name"filename 'username jsonwith open(filename' 'as f_objv json dump(usernamef_objw print("we'll remember you when you come backusername "!"at we prompt for username to store nextwe use json dump()passing it username and file objectto store the username in file then we print message informing the user that we've stored their information wwhat is your nameeric we'll remember you when you come backericnow let' write new program that greets user whose name has already been storedgreet_user py import json filename 'username jsonu with open(filenameas f_objusername json load(f_objprint("welcome backusername "!"
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 username if the file username json doesn' existwe'll have the except block prompt for username and store it in username json for next timeremember_ me py import json load the usernameif it has been stored previously otherwiseprompt for the username and store it filename 'username jsontryu with open(filenameas f_objv username json load(f_objw except filenotfounderrorx username input("what is your name" with open(filename' 'as f_objjson dump(usernamef_objprint("we'll remember you when you come backusername "!"elseprint("welcome backusername "!"there' no new code hereblocks of code from the last two examples are just combined into one file at we try to open the file username json if this file existswe read the username back into memory and print message welcoming back the user in the else block if this is the first time the user runs the programusername json won' exist and filenotfounderror will occur python will move on to the except block where we prompt the user to enter their username we then use json dump(to store the username and print greeting whichever block executesthe result is username and an appropriate greeting if this is the first time the program runsthis is the outputwhat is your nameeric we'll remember you when you come backericotherwisewelcome backericthis is the output you see if the program was already run at least once files and exceptions
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 moving the bulk of its logic into one or more functions the focus of remember_me py is on greeting the userso let' move all of our existing code into function called greet_user()remember_ me py import json def greet_user()"""greet the user by name ""filename 'username jsontrywith open(filenameas f_objusername json load(f_objexcept filenotfounderrorusername input("what is your name"with open(filename' 'as f_objjson dump(usernamef_objprint("we'll remember you when you come backusername "!"elseprint("welcome backusername "!"greet_user(because we're using function nowwe update the comments with docstring that reflects how the program currently works this file is little cleanerbut the function greet_user(is doing more than just greeting the user--it' also retrieving stored username if one exists and prompting for new username if one doesn' exist let' refactor greet_user(so it' not doing so many different tasks we'll start by moving the code for retrieving stored username to separate functionimport json def get_stored_username()"""get stored username if available ""filename 'username jsontrywith open(filenameas f_objusername json load(f_objexcept filenotfounderrorv return none elsereturn username
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 clear purposeas stated in the docstring at this function retrieves stored username and returns the username if it finds one if the file username json doesn' existthe function returns none this is good practicea function should either return the value you're expectingor it should return none this allows us to perform simple test with the return value of the function at we print welcome back message to the user if the attempt to retrieve username was successfuland if it doesn'twe prompt for new username we should factor one more block of code out of greet_user(if the username doesn' existwe should move the code that prompts for new username to function dedicated to that purposeimport json def get_stored_username()"""get stored username if available ""--snip-def get_new_username()"""prompt for new username ""username input("what is your name"filename 'username jsonwith open(filename' 'as f_objjson dump(usernamef_objreturn username def greet_user()"""greet the user by name ""username get_stored_username(if usernameprint("welcome backusername "!"elseusername get_new_username(print("we'll remember you when you come backusername "!"greet_user(files and exceptions
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 responsible only for getting new username and storing it this compartmentalization of work is an essential part of writing clear code that will be easy to maintain and extend try it yourse lf - favorite numberwrite program that prompts for the user' favorite number use json dump(to store this number in file write separate program that reads in this value and prints the message" know your favorite numberit' - favorite number rememberedcombine the two programs from exercise - into one file if the number is already storedreport the favorite number to the user if notprompt for the user' favorite number and store it in file run the program twice to see that it works - verify userthe final listing for remember_me py assumes either that the user has already entered their username or that the program is running for the first time we should modify it in case the current user is not the person who last used the program before printing welcome back message in greet_user()ask the user if this is the correct username if it' notcall get_new_username(to get the correct username summary in this you learned how to work with files you learned to read an entire file at once and read through file' contents one line at time you learned to write to file and append text onto the end of file you read about exceptions and how to handle the exceptions you're likely to see in your programs finallyyou learned how to store python data structures so you can save information your users providepreventing them from having to start over each time they run program in you'll learn efficient ways to test your code this will help you trust that the code you develop is correctand it will help you identify bugs that are introduced as you continue to build on the programs you've written
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'll also be able to test new code as you add it to make sure your changes don' break your program' existing behavior every programmer makes mistakesso every programmer must test their code oftencatching problems before users encounter them in this you'll learn to test your code using tools in python' unittest module you'll learn to build test case and check that set of inputs results in the output you want you'll see what passing test looks like and what failing test looks likeand you'll learn how failing test can help you improve your code you'll learn to test functions and classesand you'll start to understand how many tests to write for project
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 first and last name with space in between to complete full nameand then capitalizes and returns the full name to check that get_formatted_name(workslet' make program that uses this function the program names py lets users enter first and last nameand see neatly formatted full namenames py from name_function import get_formatted_name print("enter 'qat any time to quit "while truefirst input("\nplease give me first name"if first =' 'break last input("please give me last name"if last =' 'break formatted_name get_formatted_name(firstlastprint("\tneatly formatted nameformatted_name 'this program imports get_formatted_name(from name_function py the user can enter series of first and last namesand see the formatted full names that are generatedenter 'qat any time to quit please give me first namejanis please give me last namejoplin neatly formatted namejanis joplin please give me first namebob please give me last namedylan neatly formatted namebob dylan please give me first nameq we can see that the names generated here are correct but let' say we want to modify get_formatted_name(so it can also handle middle names as we do sowe want to make sure we don' break the way the function handles names that have only first and last name we could test our code
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 test cases the module unittest from the python standard library provides tools for testing your code unit test verifies that one specific aspect of function' behavior is correct test case is collection of unit tests that together prove that function behaves as it' supposed towithin the full range of situations you expect it to handle good test case considers all the possible kinds of input function could receive and includes tests to represent each of these situations test case with full coverage includes full range of unit tests covering all the possible ways you can use function achieving full coverage on large project can be daunting it' often good enough to write tests for your code' critical behaviors and then aim for full coverage only if the project starts to see widespread use passing test the syntax for setting up test case takes some getting used tobut once you've set up the test case it' straightforward to add more unit tests for your functions to write test case for functionimport the unittest module and the function you want to test then create class that inherits from unittest testcaseand write series of methods to test different aspects of your function' behavior here' test case with one method that verifies that the function get_formatted_name(works correctly when given first and last nametest_name_ function py import unittest from name_function import get_formatted_name class namestestcase(unittest testcase)"""tests for 'name_function py"" def test_first_last_name(self)"""do names like 'janis joplinwork?""formatted_name get_formatted_name('janis''joplin'self assertequal(formatted_name'janis joplin'unittest main(firstwe import unittest and the function we want to testget_formatted_ name(at we create class called namestestcasewhich will contain series of unit tests for get_formatted_name(you can name the class anything you testing your code
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 first and last name are formatted correctly any method that starts with test_ will be run automatically when we run test_name_function py within this test methodwe call the function we want to test and store return value that we're interested in testing in this example we call get_formatted_name(with the arguments 'janisand 'joplin'and store the result in formatted_name at we use one of unittest' most useful featuresan assert method assert methods verify that result you received matches the result you expected to receive in this casebecause we know get_formatted_name(is supposed to return capitalizedproperly spaced full namewe expect the value in formatted_name to be janis joplin to check if this is truewe use unittest' assertequal(method and pass it formatted_name and 'janis joplinthe line self assertequal(formatted_name'janis joplin'says"compare the value in formatted_name to the string 'janis joplinif they are equal as expectedfine but if they don' matchlet me know!the line unittest main(tells python to run the tests in this file when we run test_name_function pywe get the following outputran test in ok the dot on the first line of output tells us that single test passed the next line tells us that python ran one testand it took less than seconds to run the final ok tells us that all unit tests in the test case passed this output indicates that the function get_formatted_name(will always work for names that have first and last name unless we modify the function when we modify get_formatted_name()we can run this test again if the test case passeswe know the function will still work for names like janis joplin failing test what does failing test look likelet' modify get_formatted_name(so it can handle middle namesbut we'll do so in way that breaks the function for names with just first and last namelike janis joplin
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 timerunning the file test_name_function py gives this outputu ===================================================================== errortest_first_last_name (__main__ namestestcasew traceback (most recent call last)file "test_name_function py"line in test_first_last_name formatted_name get_formatted_name('janis''joplin'typeerrorget_formatted_name(missing required positional argument'lastx ran test in failed (errors= there' lot of information here because there' lot you might need to know when test fails the first item in the output is single uwhich tells us one unit test in the test case resulted in an error nextwe see that test_first_last_name(in namestestcase caused an error knowing which test failed is critical when your test case contains many unit tests at we see standard tracebackwhich reports that the function call get_formatted_name('janis''joplin'no longer works because it' missing required positional argument we also see that one unit test was run finallywe see an additional message that the overall test case failed and that one error occurred when running the test case this information appears at the end of the output so you see it right awayyou don' want to scroll up through long output listing to find out how many tests failed responding to failed test what do you do when test failsassuming you're checking the right conditionsa passing test means the function is behaving correctly and failing test means there' an error in the new code you wrote so when test testing your code
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 desired behavior of get_formatted_name(the best option here is to make the middle name optional once we doour test for names like janis joplin should pass againand we should be able to accept middle names as well let' modify get_formatted_name(so middle names are optional and then run the test case again if it passeswe'll move on to making sure the function handles middle names properly to make middle names optionalwe move the parameter middle to the end of the parameter list in the function definition and give it an empty default value we also add an if test that builds the full name properlydepending on whether or not middle name is providedname_ function py def get_formatted_name(firstlastmiddle='')"""generate neatly formatted full name ""if middlefull_name first middle last elsefull_name first last return full_name title(in this new version of get_formatted_name()the middle name is optional if middle name is passed to the function (if middle:)the full name will contain firstmiddleand last name otherwisethe full name will consist of just first and last name now the function should work for both kinds of names to find out if the function still works for names like janis joplinlet' run test_name_function py againran test in ok the test case passes now this is idealit means the function works for names like janis joplin again without us having to test the function manually fixing our function was easy because the failed test helped us identify the new code that broke existing behavior
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 test_first_last_name(self)"""do names like 'janis joplinwork?""formatted_name get_formatted_name('janis''joplin'self assertequal(formatted_name'janis joplin'def test_first_last_middle_name(self)"""do names like 'wolfgang amadeus mozartwork?""formatted_name get_formatted_name'wolfgang''mozart''amadeus'self assertequal(formatted_name'wolfgang amadeus mozart' unittest main(we name this new method test_first_last_middle_name(the method name must start with test_ so the method runs automatically when we run test_name_function py we name the method to make it clear which behavior of get_formatted_name(we're testing as resultif the test failswe know right away what kinds of names are affected it' fine to have long method names in your testcase classes they need to be descriptive so you can make sense of the output when your tests failand because python calls them automaticallyyou'll never have to write code that calls these methods to test the functionwe call get_formatted_name(with firstlastand middle name uand then we use assertequal(to check that the returned full name matches the full name (firstmiddleand lastthat we expect when we run test_name_function py againboth tests passran tests in ok greatwe now know that the function still works for names like janis joplinand we can be confident that it will work for names like wolfgang amadeus mozart as well testing your code
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 need to import unittest and the function you want to testwrite method called test_city_country(to verify that calling your function with values such as 'santiagoand 'chileresults in the correct string run test_cities pyand make sure test_city_country(passes - populationmodify your function so it requires third parameterpopulation it should now return single string of the form citycountry population xxxsuch as santiagochile population run test_cities py again make sure test_city_country(fails this time modify the function so the population parameter is optional run test_cities py againand make sure test_city_country(passes again write second test called test_city_country_population(that verifies you can call your function with the values 'santiago''chile'and 'population= run test_cities py againand make sure this new test passes testing class in the first part of this you wrote tests for single function now you'll write tests for class you'll use classes in many of your own programsso it' helpful to be able to prove that your classes work correctly if you have passing tests for class you're working onyou can be confident that improvements you make to the class won' accidentally break its current behavior variety of assert methods python provides number of assert methods in the unittest testcase class as mentioned earlierassert methods test whether condition you believe is true at specific point in your code is indeed true if the condition is true as expectedyour assumption about how that part of your program behaves is confirmedyou can be confident that no errors exist if the condition you assume is true is actually not truepython raises an exception table - describes six commonly used assert methods with these methods you can verify that returned values equal or don' equal expected valuesthat values are true or falseand that values are in or not in given
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 that item is in list assertnotin(itemlistverify that item is not in list class to test testing class is similar to testing function--much of your work involves testing the behavior of the methods in the class but there are few differencesso let' write class to test consider class that helps administer anonymous surveyssurvey py class anonymoussurvey()"""collect anonymous answers to survey question "" def __init__(selfquestion)"""store questionand prepare to store responses ""self question question self responses [ def show_question(self)"""show the survey question ""print(questionw def store_response(selfnew_response)"""store single response to the survey ""self responses append(new_responsex def show_results(self)"""show all the responses that have been given ""print("survey results:"for response in responsesprint('responsethis class starts with survey question that you provide and includes an empty list to store responses the class has methods to print the survey question vadd new response to the response list wand print all the responses stored in the list to create an instance from this classall you testing your code
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(questionshow the questionand store responses to the question my_survey show_question(print("enter 'qat any time to quit \ "while trueresponse input("language"if response =' 'break my_survey store_response(responseshow the survey results print("\nthank you to everyone who participated in the survey!"my_survey show_results(this program defines question ("what language did you first learn to speak?"and creates an anonymoussurvey object with that question the program calls show_question(to display the question and then prompts for responses each response is stored as it is received when all responses have been entered (the user inputs to quit)show_results(prints the survey resultswhat language did you first learn to speakenter 'qat any time to quit languageenglish languagespanish languageenglish languagemandarin languageq thank you to everyone who participated in the surveysurvey resultsenglish spanish english mandarin
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 the current behavior of the class anonymoussurvey for exampleit' possible that while trying to allow each user to enter multiple responseswe could accidentally change how single responses are handled to ensure we don' break existing behavior as we develop this modulewe can write tests for the class testing the anonymoussurvey class let' write test that verifies one aspect of the way anonymoussurvey behaves we'll write test to verify that single response to the survey question is stored properly we'll use the assertin(method to verify that the response is in the list of responses after it' been storedtest_ survey py import unittest from survey import anonymoussurvey class testanonmyoussurvey(unittest testcase)"""tests for the class anonymoussurvey"" def test_store_single_response(self)"""test that single response is stored properly ""question "what language did you first learn to speak?my_survey anonymoussurvey(questionmy_survey store_response('english'self assertin('english'my_survey responsesunittest main(we start by importing the unittest module and the class we want to testanonymoussurvey we call our test case testanonymoussurveywhich again inherits from unittest testcase the first test method will verify that when we store response to the survey questionthe response ends up in the survey' list of responses good descriptive name for this method is test_store_single_response( if this test failswe'll know from the method name shown in the output of the failing test that there was problem storing single response to the survey to test the behavior of classwe need to make an instance of the class at we create an instance called my_survey with the question "what language did you first learn to speak?we store single responseenglishusing the store_response(method then we verify that the response was stored correctly by asserting that english is in the list my_survey responses testing your code
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 anonymoussurvey""def test_store_single_response(self)"""test that single response is stored properly ""--snip-def test_store_three_responses(self)"""test that three individual responses are stored properly ""question "what language did you first learn to speak?my_survey anonymoussurvey(questionresponses ['english''spanish''mandarin'for response in responsesmy_survey store_response(responseu for response in responsesself assertin(responsemy_survey responsesv unittest main(we call the new method test_store_three_responses(we create survey object just like we did in test_store_single_response(we define list containing three different responses uand then we call store_response(for each of these responses once the responses have been storedwe write another loop and assert that each response is now in my_survey responses when we run test_survey py againboth tests (for single response and for three responsespassran tests in ok this works perfectly howeverthese tests are bit repetitiveso we'll use another feature of unittest to make them more efficient
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 the setup(method before running each method starting with test_ any objects created in the setup(method are then available in each test method you write let' use setup(to create survey instance and set of responses that can be used in test_store_single_response(and test_store_three_responses()import unittest from survey import anonymoussurvey class testanonymoussurvey(unittest testcase)"""tests for the class anonymoussurvey "" def setup(self)""create survey and set of responses for use in all test methods ""question "what language did you first learn to speak?self my_survey anonymoussurvey(questionself responses ['english''spanish''mandarin'def test_store_single_response(self)"""test that single response is stored properly ""self my_survey store_response(self responses[ ]self assertin(self responses[ ]self my_survey responsesdef test_store_three_responses(self)"""test that three individual responses are stored properly ""for response in self responsesself my_survey store_response(responsefor response in self responsesself assertin(responseself my_survey responsesunittest main(the method setup(does two thingsit creates survey instance uand it creates list of responses each of these is prefixed by selfso they can be used anywhere in the class this makes the two test methods simplerbecause neither one has to make survey instance or response the method test_store_single_response(verifies that the first response in self responses-self responses[ ]--can be stored correctlyand test_store_ single_response(verifies that all three responses in self responses can be stored correctly when we run test_survey py againboth tests still pass these tests would be particularly useful when trying to expand anonymoussurvey to handle multiple responses for each person after modifying the code to accept multiple testing your code
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 instances and attributes in each test method note when test case is runningpython prints one character for each unit test as it is completed passing test prints dota test that results in an error prints an eand test that results in failed assertion prints an this is why you'll see different number of dots and characters on the first line of output when you run your test cases if test case takes long time to run because it contains many unit testsyou can watch these results to get sense of how many tests are passing try it yourse lf - employeewrite class called employee the __init__(method should take in first namea last nameand an annual salaryand store each of these as attributes write method called give_raise(that adds $ to the annual salary by default but also accepts different raise amount write test case for employee write two test methodstest_give_ default_raise(and test_give_custom_raise(use the setup(method so you don' have to create new employee instance in each test method run your test caseand make sure both tests pass summary in this you learned to write tests for functions and classes using tools in the unittest module you learned to write class that inherits from unittest testcaseand you learned to write test methods that verify specific behaviors your functions and classes should exhibit you learned to use the setup(method to efficiently create instances and attributes from your classes that can be used in all the test methods for class testing is an important topic that many beginners don' learn you don' have to write tests for all the simple projects you try as beginner but as soon as you start to work on projects that involve significant development effortyou should test the critical behaviors of your functions and classes you'll be more confident that new work on your project won' break the parts that workand this will give you the freedom to make improvements to your code if you accidentally break existing functionalityyou'll know right awayso you can still fix the problem easily responding to failed test that you ran is much easier than responding to bug report from an unhappy user
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 with the process of testing your code write tests for the most critical behaviors of your functions and classesbut don' aim for full coverage in early projects unless you have specific reason to do so testing your code
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 projects in whichever order you like here' brief description of each project to help you decide which to dig into first alien invasionmaking game with python in the alien invasion project and )you'll use the pygame package to develop game in which the aim is to shoot down fleet of aliens as they drop down the screen in levels that increase in speed and difficulty at the end of the projectyou'll have learned skills that will enable you to develop your own games in pygame data visualization the data visualization project starts in in which you'll learn to generate data and create series of functional and beautiful visualizations of that data using matplotlib and pygal teaches you to access data from online sources and feed it into visualization package to create plots of weather data and world population map finally
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've been learning about users will create an account with username and passwordenter topicand then make entries about what they're learning you'll also learn how to deploy your app so anyone in the world can access it after completing this projectyou'll be able to start building your own simple web applicationsand you'll be ready to delve into more thorough resources on building applications with django part ii
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 logic of game dynamics in this you'll set up pygame and then create ship that moves right and leftand fires bullets in response to player input in the next two you'll create fleet of aliens to destroyand then continue to make refinementssuch as setting limits on the number of ships you can use and adding scoreboard from this you'll also learn to manage large projects that span multiple files we'll refactor lot of code and manage file contents to keep our project organized and the code efficient
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 understanding of how to refine interactions in your own games note alien invasion will span number of different filesso make new folder on your system called alien_invasion be sure to save all files for the project to this folder so your import statements will work correctly planning your project when building large projectit' important to prepare plan before you begin to write your code your plan will keep you focused and make it more likely that you'll complete the project let' write description of the overall gameplay although this description doesn' cover every detail of alien invasionit provides clear idea of how to start building the gamein alien invasionthe player controls ship that appears at the bottom center of the screen the player can move the ship right and left using the arrow keys and shoot bullets using the spacebar when the game beginsa fleet of aliens fills the sky and moves across and down the screen the player shoots and destroys the aliens if the player shoots all the aliensa new fleet appears that moves faster than the previous fleet if any alien hits the player' ship or reaches the bottom of the screenthe player loses ship if the player loses three shipsthe game ends for the first phase of developmentwe'll make ship that can move right and left the ship should be able to fire bullets when the player presses the spacebar after setting up this behaviorwe can turn our attention to the aliens and refine the gameplay installing pygame before you begin codinginstall pygame here' how to do so on linuxos xand microsoft windows if you're using python on linux or if you're using os xyou'll need to use pip to install pygame pip is program that handles the downloading and installing of python packages for you the following sections will show you how to install packages with pip if you're using python on linux or if you're using windowsyou won' need pip to install pygame insteadmove on to "installing pygame on linuxon page or "installing pygame on windowson page
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 instructions work for you installing python packages with pip the most recent versions of python come with pip installedso first check whether pip is already on your system with python pip is sometimes called pip checking for pip on linux and os open terminal window and enter the following commandpip --version pip from /usr/local/lib/python /dist-packages (python if you have only one version of python installed on your system and you see output similar to thismove on to either "installing pygame on linuxon page or "installing pygame on os xon page if you get an error messagetry using pip instead of pip if neither version is installed on your systemgo to "installing pipon page if you have more than one version of python on your systemverify that pip is associated with the version of python you're using--for examplepython at if pip is associated with the correct version of pythonmove on to "installing pygame on linuxon page or "installing pygame on os xon page if pip is associated with the wrong version of pythontry using pip instead of pip if neither command works for the version of python you're usinggo to "installing pipon page checking for pip on windows open terminal window and enter the following commandpython - pip --version pip from :\python \lib\site-packages (python if your system has only one version of python installed and you see output similar to thismove on to "installing pygame on windowson page if you get an error messagetry using pip instead of pip if neither version is installed on your systemmove on to "installing pipon page if your system has more than one version of python installedverify that pip is associated with the version of python you're using--for examplepython at if pip is associated with the correct version of pythonmove on to "installing pygame on windowson page if pip is associated with ship that fires bullets
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 packages to your system note if you can' find get-pip pygo to paneland then under "install pip,follow the link to get-pip py installing pip on linux and os use the following command to run get-pip py with administrative privilegessudo python get-pip py note if you use the command python to start terminal sessionyou should use sudo python get-pip py here after the program runsuse the command pip --version (or pip --versionto make sure pip was installed correctly installing pip on windows use the following command to run get-pip pypython get-pip py if you use different command to run python in terminalmake sure you use that command to run get-pip py for exampleyour command might be python get-pip py or :\python \python get-pip py after the program runsrun the command python - pip --version to make sure pip was installed successfully installing pygame on linux if you're using python install pygame using the package manager open terminal window and run the following commandwhich will download and install pygame onto your systemsudo apt-get install python-pygame
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 (if you use command such as python on your systemreplace python -dev with python -dev sudo apt-get install python -dev mercurial sudo apt-get install libsdl-image -dev libsdl -dev libsdl-ttf -dev this will install the libraries needed to run alien invasion successfully if you want to enable some more advanced functionality in pygamesuch as the ability to add soundsyou can also add the following librariessudo apt-get install libsdl-mixer -dev libportmidi-dev sudo apt-get install libswscale-dev libsmpeg-dev libavformat-dev libavcode-dev sudo apt-get install python-numpy now install pygame by entering the following (use pip if that' appropriate for your system)pip install --user hg+the output will pause for moment after informing you which libraries pygame found press entereven though some libraries are missing you should see message stating that pygame installed successfully to confirm the installationrun python terminal session and try to import pygame by entering the followingpython import pygame if this worksmove on to "starting the game projecton page installing pygame on os you'll need homebrew to install some packages that pygame depends on if you haven' already installed homebrewsee appendix for instructions to install the libraries that pygame depends onenter the followingbrew install hg sdl sdl_image sdl_ttf ship that fires bullets
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 --user hg+start python terminal session and import pygame to check whether the installation was successful (enter python rather than python if you're running python )python import pygame if the import statement worksmove on to "starting the game projectbelow installing pygame on windows the pygame project is hosted on code-sharing site called bitbucket to install pygame on your version of windowsfind windows installer at python you're running if you don' see an appropriate installer listed at bitbucketcheck after you've downloaded the appropriate filerun the installer if it' exe file if you have file ending in whlcopy the file to your project directory open command windownavigate to the folder that you copied the installer toand use pip to run the installerpython - pip install --user pygame- -cp -none-win whl starting the game project now we'll start building our game by first creating an empty pygame window to which we can later draw our game elementssuch as the ship and the aliens we'll also have our game respond to user inputset the background colorand load ship image
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 truewatch for keyboard and mouse events for event in pygame event get()if event type =pygame quitsys exit(make the most recently drawn screen visible pygame display flip(run_game(firstwe import the sys and pygame modules the pygame module contains the functionality needed to make game we'll use the sys module to exit the game when the player quits alien invasion starts as the function run_game(the line pygame init(at initializes background settings that pygame needs to work properly at vwe call pygame display set_mode(to create display window called screenon which we'll draw all of the game' graphical elements the argument ( is tuple that defines the dimensions of the game window by passing these dimensions to pygame display set_mode()we create game window pixels wide by pixels high (you can adjust these values depending on the size of your display the screen object is called surface surface in pygame is part of the screen where you display game element each element in the gamelike the aliens or the shipis surface the surface returned by display set_mode(represents the entire game window when we activate the game' animation loopthis surface is automatically redrawn on every pass through the loop the game is controlled by while loop that contains an event loop and code that manages screen updates an event is an action that the user performs while playing the gamesuch as pressing key or moving the mouse to make our program respond to eventswe'll write an event loop to listen for an event and perform an appropriate task depending on the kind of event that occurred the for loop at is an event loop ship that fires bullets
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 flip(at tells pygame to make the most recently drawn screen visible in this case it draws an empty screen each time through the while loop to erase the old screen so that only the new screen is visible when we move the game elements aroundpygame display flip(will continually update the display to show the new positions of elements and hide the old onescreating the illusion of smooth movement the last line in this basic game structure calls run_game()which initializes the game and starts the main loop run this code nowand you should see an empty pygame window setting the background color pygame creates black screen by defaultbut that' boring let' set different background coloralien_ invasion py --snip-def run_game()--snip-pygame display set_caption("alien invasion" set the background color bg_color ( start the main loop for the game while truewatch for keyboard and mouse events --snip- redraw the screen during each pass through the loop screen fill(bg_colormake the most recently drawn screen visible pygame display flip(run_game(firstwe create background color and store it in bg_color this color needs to be specified only onceso we define its value before entering the main while loop colors in pygame are specified as rgb colorsa mix of redgreenand blue each color value can range from to the color value ( is red( is greenand ( is blue you can mix rgb values to create million colors the color value ( mixes equal amounts of redblueand greenwhich produces light gray background color
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 one place this approach allows us to pass around one settings object instead of many individual settings in additionit makes our function calls simpler and makes it easier to modify the game' appearance as our project grows to modify the gamewe'll simply change some values in settings py instead of searching for different settings throughout our files here' the initial settings classsettings py class settings()""" class to store all settings for alien invasion ""def __init__(self)"""initialize the game' settings ""screen settings self screen_width self screen_height self bg_color ( to make an instance of settings and use it to access our settingsmodify alien_invasion py as followsalien_ invasion py --snip-import pygame from settings import settings def run_game()initialize pygamesettingsand screen object pygame init( ai_settings settings( screen pygame display set_mode(ai_settings screen_widthai_settings screen_height)pygame display set_caption("alien invasion" start the main loop for the game while true--snip-redraw the screen during each pass through the loop screen fill(ai_settings bg_colormake the most recently drawn screen visible pygame display flip(run_game( ship that fires bullets
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 our game to draw the player' ship on screenwe'll load an image and then use the pygame method blit(to draw the image when choosing artwork for your gamesbe sure to pay attention to licensing the safest and cheapest way to start is to use freely licensed graphics that you can modify from website like you can use almost any type of image file in your gamebut it' easiest if you use bitmap bmpfile because pygame loads bitmaps by default although you can configure pygame to use other file typessome file types depend on certain image libraries that must be installed on your computer (most images you'll find are in jpgpngor gif formatsbut you can convert them to bitmaps using tools like photoshopgimpand paint pay particular attention to the background color in your chosen image try to find file with transparent background that you can replace with any background color using an image editor your games will look best if the image' background color matches your game' background color alternativelyyou can match your game' background to the image' background for alien invasionyou can use the file ship bmp (figure - )which is available in the book' resources through pythoncrashcoursethe file' background color matches the settings we're using in this project make folder called images inside your main project folder (alien_invasionsave the file ship bmp in the images folder figure - the ship for alien invasion
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 ""self screen screen load the ship image and get its rect self image pygame image load('images/ship bmp'self rect self image get_rect(self screen_rect screen get_rect(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 def blitme(self)"""draw the ship at its current location ""self screen blit(self imageself rectfirstwe import the pygame module the __init__(method of ship takes two parametersthe self reference and the screen where we'll draw the ship to load the imagewe call pygame image load( this function returns surface representing the shipwhich we store in self image once the image is loadedwe use get_rect(to access the surface' rect attribute one reason pygame is so efficient is that it lets you treat game elements like rectangles (rects)even if they're not exactly shaped like rectangles treating an element as rectangle is efficient because rectangles are simple geometric shapes this approach usually works well enough that no one playing the game will notice that we're not working with the exact shape of each game element when working with rect objectyou can use the xand -coordinates of the topbottomleftand right edges of the rectangleas well as the center you can set any of these values to determine the current position of the rect when you're centering game elementwork with the centercenterxor centery attributes of rect when you're working at an edge of the screenwork with the topbottomleftor right attributes when you're adjusting the horizontal or vertical placement of the rectyou can just use the and attributeswhich are the xand -coordinates of its top-left corner these attributes spare you from having to do calculations that game developers formerly had to do manuallyand you'll find you'll use them often ship that fires bullets
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 -coordinate of the ship' centermatch the centerx attribute of the screen' rect make the value of self rect bottom (the -coordinate of the ship' bottomequal to the value of the screen rect' bottom attribute pygame will use these rect attributes to position the ship image so it' centered horizontally and aligned with the bottom of the screen at we define the blitme(methodwhich will draw the image to the screen at the position specified by self rect drawing the ship to the screen now let' update alien_invasion py so it creates ship and calls the ship' blitme(methodalien_ invasion py --snip-from settings import settings from ship import ship def run_game()--snip-pygame display set_caption("alien invasion" make ship ship ship(screenv start the main loop for the game while true--snip-redraw the screen during each pass through the loop screen fill(ai_settings bg_colorship blitme(make the most recently drawn screen visible pygame display flip(run_game(we import ship and then make an instance of ship (named shipafter the screen has been created it must come before the main while loop so we don' make new instance of the ship on each pass through the loop we draw the ship onscreen by calling ship blitme(after filling the backgroundso the ship appears on top of the background when you run alien_invasion py nowyou should see an empty game screen with our rocket ship sitting at the bottom centeras shown in figure -
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 that make alien invasion work the game_functions module will prevent alien_invasion py from becoming too lengthy and will make the logic in alien_invasion py easier to follow the check_events(function we'll start by moving the code that manages events to separate function called check_events(this will simplify run_game(and isolate the event management loop isolating the event loop allows you to manage events separately from other aspects of the gamelike updating the screen place check_events(in separate module called game_functionsgame_ functions py import sys import pygame def check_events()"""respond to keypresses and mouse events ""for event in pygame event get()if event type =pygame quitsys exit( ship that fires bullets
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 the main loop for the game while truegf check_events(redraw the screen during each pass through the loop --snip-we no longer need to import sys directly into the main program filebecause it' only being used in the game_functions module now we give the imported game_functions module the alias gf for simplification the update_screen(function let' move the code for updating the screen to separate function called update_screen(in game_functions py to further simplify run_game()game_ functions py --snip-def check_events()--snip-def update_screen(ai_settingsscreenship)"""update images on the screen and flip to the new screen ""redraw the screen during each pass through the loop screen fill(ai_settings bg_colorship blitme(make the most recently drawn screen visible pygame display flip(the new update_screen(function takes three parametersai_settingsscreenand ship now we need to update the while loop from alien_invasion py with call to update_screen()alien_ invasion py --snip-start the main loop for the game
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' introduce the game_functions module right away this approach gives you an idea of realistic development processyou start out writing your code as simply as possibleand refactor it as your project becomes more complex now that our code is restructured to make it easier to add towe can work on the dynamic aspects of the gametry it yourse lf - blue skymake pygame window with blue background - game characterfind bitmap image of game character you like or convert an image to bitmap make class that draws the character at the center of the screen and match the background color of the image to the background color of the screenor vice versa piloting the ship let' give the player the ability to move the ship right and left to do thiswe'll write code that responds when the player presses the right or left arrow key we'll focus on movement to the right firstand then we'll apply the same principles to control movement to the left as you do thisyou'll learn how to control the movement of images on the screen responding to keypress whenever the player presses keythat keypress is registered in pygame as an event each event is picked up by the pygame event get(methodso we need to specify in our check_events(function what kind of events to check for each keypress is registered as keydown event when keydown event is detectedwe need to check whether the key that was pressed is one that triggers certain event for exampleif the ship that fires bullets
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 ship parameterbecause the ship needs to move to the right when the right arrow key is pressed inside check_events(we add an elif block to the event loop to respond when pygame detects keydown event we check if the key pressed is the right arrow key (pygame k_rightby reading the event key attribute if the right arrow key was pressedwe move the ship to the right by increasing the value of ship rect centerx by we need to update the call to check_events(in alien_invasion py so it passes ship as an argumentalien_ invasion py start the main loop for the game while truegf check_events(shipgf update_screen(ai_settingsscreenshipif you run alien_invasion py nowyou should see the ship move to the right one pixel every time you press the right arrow key that' startbut it' not an efficient way to control the ship let' improve this control by allowing continuous movement allowing continuous movement when the player holds down the right arrow keywe want the ship to continue moving right until the player releases the key we'll have our game detect pygame keyup event so we'll know when the right arrow key is releasedthen we'll use the keydown and keyup events together with flag called moving_right to implement continuous motion when the ship is motionlessthe moving_right flag will be false when the right arrow key is pressedwe'll set the flag to trueand when it' releasedwe'll set the flag to false again the ship class controls all attributes of the shipso we'll give it an attribute called moving_right and an update(method to check the status of the moving_right flag the update(method will change the position of the ship if the flag is set to true we'll call this method any time we want to update the position of the ship
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_rightself rect centerx + def blitme(self)--snip-we add self moving_right attribute in the __init__(method and set it to false initially then we add update()which moves the ship right if the flag is true now modify check_events(so that moving_right is set to true when the right arrow key is pressed and false when the key is releasedgame_ functions py def check_events(ship)"""respond to keypresses and mouse events ""for event in pygame event get()--snip-elif event type =pygame keydownif event key =pygame k_rightu ship moving_right true elif event type =pygame keyupif event key =pygame k_rightship moving_right false at uwe modify how the game responds when the player presses the right arrow keyinstead of changing the ship' position directlywe merely set moving_right to true at vwe add new elif blockwhich responds to keyup events when the player releases the right arrow key (k_right)we set moving_right to false finallywe modify the while loop in alien_invasion py so it calls the ship' update(method on each pass through the loopalien_ invasion py start the main loop for the game while truegf check_events(shipship update(gf update_screen(ai_settingsscreenshipa ship that fires bullets
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 the key moving both left and right now that the ship can move continuously to the rightadding movement to the left is easy we'll again modify the ship class and the check_events(function here are the relevant changes to __init__(and update(in shipship py def __init__(selfscreen)--snip-movement flags self moving_right false self moving_left false def update(self)"""update the ship' position based on movement flags ""if self moving_rightself rect centerx + if self moving_leftself rect centerx - in __init__()we add self moving_left flag in update()we use two separate if blocks rather than an elif in update(to allow the ship' rect centerx value to be increased and then decreased if both arrow keys are held down this results in the ship standing still if we used elif for motion to the leftthe right arrow key would always have priority doing it this way makes the movements more accurate when switching from left to rightwhen the player might momentarily hold down both keys we have to make two adjustments to check_events()game_ functions py def check_events(ship)"""respond to keypresses and mouse events ""for event in pygame event get()--snip-elif event type =pygame keydownif event key =pygame k_rightship moving_right true elif event key =pygame k_leftship moving_left true elif event type =pygame keyupif event key =pygame k_rightship moving_right false elif event key =pygame k_leftship moving_left false
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 if you hold down both keysthe ship should stop moving nextwe'll further refine the movement of the ship let' adjust the ship' speed and limit how far the ship can move so it doesn' disappear off the sides of the screen adjusting the ship' speed currentlythe ship moves one pixel per cycle through the while loopbut we can take finer control of the ship' speed by adding ship_speed_factor attribute to the settings class we'll use this attribute to determine how far to move the ship on each pass through the loop here' the new attribute in settings pysettings py class settings()""" class to store all settings for alien invasion ""def __init__(self)--snip-ship settings self ship_speed_factor we set the initial value of ship_speed_factor to when we want to move the shipwe'll adjust its position by pixels rather than pixel we're using decimal values for the speed setting to give us finer control of the ship' speed when we increase the tempo of the game later on howeverrect attributes such as centerx store only integer valuesso we need to make some modifications to shipship py class ship() def __init__(selfai_settingsscreen)"""initialize the ship and set its starting position ""self screen screen self ai_settings ai_settings --snip-start each new ship at the bottom center of the screen --snip- store decimal value for the ship' center self center float(self rect centerxmovement flags self moving_right false self moving_left false ship that fires bullets
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 blitme(self)--snip-at uwe add ai_settings to the list of parameters for __init__()so the ship will have access to its speed setting we then turn the ai_settings parameter into an attributeso we can use it in update( now that we're adjusting the position of the ship by fractions of pixelwe need to store the position in variable that can store decimal value you can use decimal value to set rect' attributebut the rect will store only the integer portion of that value to store the ship' position accuratelywe define new attribute self centerwhich can hold decimal values we use the float(function to convert the value of self rect centerx to decimal and store this value in self center now when we change the ship' position in update()the value of self center is adjusted by the amount stored in ai_settings ship_speed_ factor after self center has been updatedwe use the new value to update self rect centerxwhich controls the position of the ship only the integer portion of self center will be stored in self rect centerxbut that' fine for displaying the ship we need to pass ai_settings as an argument when we create an instance of ship in alien_invasion pyalien_ invasion py --snip-def run_game()--snip-make ship ship ship(ai_settingsscreen--snip-now any value of ship_speed_factor greater than one will make the ship move faster this will be helpful in making the ship respond quickly enough to shoot down aliensand it will let us change the tempo of the game as the player progresses in gameplay
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 ""update the ship' center valuenot the rect if self moving_right and self rect right self screen_rect rightself center +self ai_settings ship_speed_factor if self moving_left and self rect left self center -self ai_settings ship_speed_factor update rect object from self center self rect centerx self center this code checks the position of the ship before changing the value of self center the code self rect right returns the -coordinate value of the right edge of the ship' rect if this value is less than the value returned by self screen_rect rightthe ship hasn' reached the right edge of the screen the same goes for the left edgeif the value of the left side of the rect is greater than zerothe ship hasn' reached the left edge of the screen this ensures the ship is within these bounds before adjusting the value of self center if you run alien_invasion py nowthe ship should stop moving at either edge of the screen refactoring check_events(the check_events(function will increase in length as we continue to develop the gameso let' break check_events(into two more functionsone that handles keydown events and another that handles keyup eventsgame_ functions py def check_keydown_events(eventship)"""respond to keypresses ""if event key =pygame k_rightship moving_right true elif event key =pygame k_leftship moving_left true def check_keyup_events(eventship)"""respond to key releases ""if event key =pygame k_rightship moving_right false elif event key =pygame k_leftship moving_left false ship that fires bullets
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 parameter and ship parameter the bodies of these two functions are copied from check_events()and we've replaced the old code with calls to the new functions the check_events(function is simpler now with this cleaner code structurewhich will make it easier to develop further responses to player input quick recap in the next sectionwe'll add the ability to shoot bulletswhich involves new file called bullet py and some modifications to some of the files we already have right nowwe have four files containing number of classesfunctionsand methods to be clear about how the project is organizedlet' review each of these files before adding more functionality alien_invasion py the main filealien_invasion pycreates number of important objects used throughout the gamethe settings are stored in ai_settingsthe main display surface is stored in screenand ship instance is created in this file as well also stored in alien_invasion py is the main loop of the gamewhich is while loop that calls check_events()ship update()and update_screen(alien_invasion py is the only file you need to run when you want to play alien invasion the other files--settings pygame_functions pyship py-contain code that is importeddirectly or indirectlyinto this file settings py the settings py file contains the settings class this class only has an __init__(methodwhich initializes attributes controlling the game' appearance and the ship' speed game_functions py the game_functions py file contains number of functions that carry out the bulk of the work in the game the check_events(function detects relevant eventssuch as keypresses and releasesand processes each of these types of events through the helper functions check_keydown_events(and
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 ship is stored in ship bmpwhich is in the images folder try it yourse lf - rocketmake game that begins with rocket in the center of the screen allow the player to move the rocket updownleftor right using the four arrow keys make sure the rocket never moves beyond any edge of the screen - keysmake pygame file that creates an empty screen in the event loopprint the event key attribute whenever pygame keydown event is detected run the program and press various keys to see how pygame responds shooting bullets now let' add the ability to shoot bullets we'll write code that fires bullet ( small rectanglewhen the player presses the spacebar bullets will then travel straight up the screen until they disappear off the top of the screen adding the bullet settings firstupdate settings py to include the values we'll need for new bullet classat the end of the __init__(methodsettings py def __init__(self)--snip-bullet settings self bullet_speed_factor self bullet_width self bullet_height self bullet_color these settings create dark gray bullets with width of pixels and height of pixels the bullets will travel slightly slower than the ship ship that fires bullets
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(bulletself__init__(self screen screen create bullet rect at ( and then set correct position self rect pygame rect( ai_settings bullet_widthai_settings bullet_heightself rect centerx ship rect centerx self rect top ship rect top store the bullet' position as decimal value self float(self rect yu self color ai_settings bullet_color self speed_factor ai_settings bullet_speed_factor the bullet class inherits from spritewhich we import from the pygame sprite module when you use spritesyou can group related elements in your game and act on all the grouped elements at once to create bullet instance__init__(needs the ai_settingsscreenand ship instancesand we call super(to inherit properly from sprite note the call super(bulletself__init__(uses python syntax this works in python tooor you can also write this call more simply as super(__init__(at uwe create the bullet' rect attribute the bullet is not based on an image so we have to build rect from scratch using the pygame rect(class this class requires the xand -coordinates of the top-left corner of the rectand the width and height of the rect we initialize the rect at ( )but we'll move it to the correct location in the next two linesbecause the bullet' position is dependent on the ship' position we get the width and height of the bullet from the values stored in ai_settings at vwe set the bullet' centerx to be the same as the ship' rect centerx the bullet should emerge from the top of the shipso we set the top of the bullet' rect to match the top of the ship' rectmaking it look like the bullet is fired from the ship we store decimal value for the bullet' -coordinate so we can make fine adjustments to the bullet' speed at ywe store the bullet' color and speed settings in self color and self speed_factor
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 when bullet is firedit moves up the screenwhich corresponds to decreasing -coordinate valueso to update the positionwe subtract the amount stored in self speed_factor from self we then use the value of self to set the value of self rect the speed_factor attribute allows us to increase the speed of the bullets as the game progresses or as needed to refine the game' behavior once fireda bullet' -coordinate value never changesso it will only travel vertically in straight line when we want to draw bulletwe'll call draw_bullet(the draw rect(function fills the part of the screen defined by the bullet' rect with the color stored in self color storing bullets in group now that we have bullet class and the necessary settings definedwe can write code to fire bullet each time the player presses the spacebar firstwe'll create group in alien_invasion py to store all the live bullets so we can manage the bullets that have already been fired this group will be an instance of the class pygame sprite groupwhich behaves like list with some extra functionality that' helpful when building games we'll use this group to draw bullets to the screen on each pass through the main loop and to update each bullet' positionalien_ invasion py import pygame from pygame sprite import group --snip-def run_game()--snip-make ship ship ship(ai_settingsscreenmake group to store bullets in bullets group(start the main loop for the game while truegf check_events(ai_settingsscreenshipbulletsship update( ship that fires bullets
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 loopyou'll be creating thousands of groups of bullets and your game will probably slow to crawl if your game freezes uplook carefully at what' happening in your main while loop we pass bullets to check_events(and update_screen(we'll need to work with bullets in check_events(when the spacebar is pressedand we'll need to update the bullets that are being drawn to the screen in update_screen(when you call update(on group vthe group automatically calls update(for each sprite in the group the line bullets update(calls bullet update(for each bullet we place in the group bullets firing bullets in game_functions pywe need to modify check_keydown_events(to fire bullet when the spacebar is pressed we don' need to change check_keyup_events(because nothing happens when the key is released we also need to modify update_screen(to make sure each bullet is redrawn to the screen before we call flip(here are the relevant changes to game_functions pygame_ functions py --snip-from bullet import bullet def check_keydown_events(eventai_settingsscreenshipbullets)--snip- elif event key =pygame k_spacecreate new bullet and add it to the bullets group new_bullet bullet(ai_settingsscreenshipbullets add(new_bullet--snip- def check_events(ai_settingsscreenshipbullets)"""respond to keypresses and mouse events ""for event in pygame event get()--snip-elif event type =pygame keydowncheck_keydown_events(eventai_settingsscreenshipbullets--snip- def update_screen(ai_settingsscreenshipbullets)--snip-redraw all bullets behind ship and aliens for bullet in bullets sprites()bullet draw_bullet(
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 in the definition of check_ events(wand we need to pass bullets as an argument in the call to check_keydown_events(as well we give the bullets parameter to update_screen(at xwhich draws the bullets to the screen the bullets sprites(method returns list of all sprites in the group bullets to draw all fired bullets to the screenwe loop through the sprites in bullets and call draw_bullet(on each one if you run alien_invasion py nowyou should be able to move the ship right and leftand fire as many bullets as you want the bullets travel up the screen and disappear when they reach the topas shown in figure - you can alter the sizecolorand speed of the bullets in settings py figure - the ship after firing series of bullets deleting old bullets at the momentthe bullets disappear when they reach the topbut only because pygame can' draw them above the top of the screen the bullets actually continue to existtheir -coordinate values just grow increasingly negative this is problembecause they continue to consume memory and processing power ship that fires bullets
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 bullets that have disappeared for bullet in bullets copy()if bullet rect bottom < bullets remove(bulletprint(len(bullets)gf update_screen(ai_settingsscreenshipbulletsyou shouldn' remove items from list or group within for loopso we have to loop over copy of the group we use the copy(method to set up the for loop uwhich enables us to modify bullets inside the loop we check each bullet to see whether it has disappeared off the top of the screen at if it haswe remove it from bullets at we insert print statement to show how many bullets currently exist in the game and verify that they're being deleted if this code works correctlywe can watch the terminal output while firing bullets and see that the number of bullets decreases to zero after each set of bullets has cleared the top of the screen after you run the game and verify that bullets are deleted properlyremove the print statement if you leave it inthe game will slow down significantly because it takes more time to write output to the terminal than it does to draw graphics to the game window limiting the number of bullets many shooting games limit the number of bullets player can have on the screen at one time to encourage players to shoot accurately we'll do the same in alien invasion firststore the number of bullets allowed in settings pysettings py bullet settings self bullet_width self bullet_height self bullet_color self bullets_allowed
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_bullet bullet(ai_settingsscreenshipbullets add(new_bulletwhen the spacebar is pressedwe check the length of bullets if len(bulletsis less than threewe create new bullet but if three bullets are already activenothing happens when the spacebar is pressed if you run the game nowyou should be able to fire bullets only in groups of three creating the update_bullets(function we want to keep our main alien_invasion py program file as simple as possibleso now that we've written and checked the bullet management code we can move it to the game_functions module we'll create new function called update_bullets(and add it to the end of game_functions pygame_ functions py def update_bullets(bullets)"""update position of bullets and get rid of old bullets ""update bullet positions bullets update(get rid of bullets that have disappeared for bullet in bullets copy()if bullet rect bottom < bullets remove(bulletthe code for update_bullets(is cut and pasted from alien_invasion pythe only parameter it needs is the group bullets the while loop in alien_invasion py looks simple againalien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenshipbulletsship update(gf update_bullets(bulletsgf update_screen(ai_settingsscreenshipbulletswe've made it so that our main loop contains only minimal code so we can quickly read the function names and understand what' happening in the game the main loop checks for player input at uand then it updates the position of the ship at and any bullets that have been fired at we then use the updated positions to draw new screen at ship that fires bullets
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_settingsscreenshipbulletsdef fire_bullet(ai_settingsscreenshipbullets)"""fire bullet if limit not reached yet ""create new bullet and add it to the bullets group if len(bulletsai_settings bullets_allowednew_bullet bullet(ai_settingsscreenshipbullets add(new_bulletthe function fire_bullet(simply contains the code that was used to fire bullet when the spacebar is pressedand we add call to fire_bullet(in check_keydown_events(when the spacebar is pressed run alien_invasion py one more timeand make sure you can still fire bullets without errors try it yourse lf - sideways shooterwrite game that places ship on the left side of the screen and allows the player to move the ship up and down make the ship fire bullet that travels right across the screen when the player presses the spacebar make sure bullets are deleted once they disappear off the screen summary in this you learned to make plan for game you learned the basic structure of game written in pygame you learned to set background color and store settings in separate class where they can be made available to all parts of the game you saw how to draw an image to the screen and give the player control over the movement of game elements you learned to create elements that move on their ownlike bullets flying up screenand how to delete objects that are no longer needed you learned to refactor code in project on regular basis to facilitate ongoing development in we'll add aliens to alien invasion by the end of you'll be able to shoot down alienshopefully before they reach your ship
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 runs out of ships as you work through this you'll learn more about pygame and about managing larger project you'll also learn to detect collisions between game objectslike bullets and aliens detecting collisions helps you define interactions between elements in your gamesyou can confine character inside the walls of maze or pass ball between two characters we'll also continue to work from plan that we revisit occasionally to maintain the focus of our code-writing sessions before we start writing new code to add fleet of aliens to the screenlet' look at the project and update our plan
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 corner of the screen with appropriate spacing around it use the spacing around the first alien and the overall screen size to determine how many aliens can fit on the screen we'll write loop to create aliens to fill the upper portion of the screen make the fleet move sideways and down until the entire fleet is shot downan alien hits the shipor an alien reaches the ground if the whole fleet is shot downwe'll create new fleet if an alien hits the ship or the groundwe'll destroy the ship and create new fleet limit the number of ships the player can useand end the game when the player has used up the allotment of ships we'll refine this plan as we implement featuresbut this is sufficient to start with you should also review code when you're about to begin working on new series of features in project because each new phase typically makes project more complexit' best to clean up cluttered or inefficient code although we don' have much cleanup to do right now because we've been refactoring as we goit' annoying to use the mouse to close the game each time we run it to test new feature let' quickly add keyboard shortcut to end the game when the user presses qgame_ functions py def check_keydown_events(eventai_settingsscreenshipbullets)--snip-elif event key =pygame k_qsys exit(in check_keydown_events(we add new block that ends the game when is pressed this is fairly safe change because the key is far from the arrow keys and the spacebarso it' unlikely player will accidentally press and quit the game nowwhen testingyou can press to close the game rather than using your mouse to close the window creating the first alien placing one alien on the screen is like placing ship on the screen the behavior of each alien is controlled by class called alienwhich we'll structure like the ship class we'll continue using bitmap images for simplicity you can find your own image for an alien or use the one
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)"""initialize the alien and set its starting position ""super(alienself__init__(self screen screen self ai_settings ai_settings load the alien image and set its rect attribute self image pygame image load('images/alien bmp'self rect self image get_rect( start each new alien near the top left of the screen self rect self rect width self rect self rect height store the alien' exact position self float(self rect xdef blitme(self)"""draw the alien at its current location ""self screen blit(self imageself rectaliens
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 alien import alien import game_functions as gf def run_game()--snip-make an alien alien alien(ai_settingsscreenstart the main loop for the game while truegf check_events(ai_settingsscreenshipbulletsship update(gf update_bullets(bulletsgf update_screen(ai_settingsscreenshipalienbulletsrun_game(here we're importing the new alien class and creating an instance of alien just before entering the main while loop because we're not changing the alien' position yetwe aren' adding anything new inside the loophoweverwe do modify the call to update_screen(to pass it the alien instance making the alien appear onscreen to make the alien appear onscreenwe call its blitme(method in update_screen()game_ functions py def update_screen(ai_settingsscreenshipalienbullets)--snip-redraw all bullets behind ship and aliens for bullet in bulletsbullet draw_bullet(ship blitme(alien blitme(make the most recently drawn screen visible pygame display flip(
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 screen and how many rows of aliens can fit down the screen we'll first figure out the horizontal spacing between aliens and create rowthen we'll determine the vertical spacing and create an entire fleet determining how many aliens fit in row to figure out how many aliens fit in rowlet' look at how much horizontal space we have the screen width is stored in ai_settings screen_widthbut we need an empty margin on either side of the screen we'll make this margin the width of one alien because we have two marginsthe available space for aliens is the screen width minus two alien widthsavailable_space_x ai_settings screen_width ( alien_widthaliens
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 calculations when we create the fleet one great aspect about calculations in programming is that you don' have to be sure your formula is correct when you first write it you can try it out and see if it works at worstyou'll have screen that' overcrowded with aliens or has too few aliens you can revise your calculation based on what you see on the screen note creating rows of aliens to create rowfirst create an empty group called aliens in alien_invasion py to hold all of our aliensand then call function in game_functions py to create fleetalien_ invasion py import pygame from pygame sprite import group from settings import settings from ship import ship import game_functions as gf def run_game()--snip-make shipa group of bulletsand group of aliens ship ship(ai_settingsscreenbullets group( aliens group( create the fleet of aliens gf create_fleet(ai_settingsscreenaliensw start the main loop for the game while true--snip-gf update_screen(ai_settingsscreenshipaliensbulletsrun_game(because we're no longer creating aliens directly in alien_invasion pywe don' need to import the alien class into this file create an empty group to hold all of the aliens in the game thencall the new function create_fleet(vwhich we'll write shortlyand pass it the ai_settingsthe screen objectand the empty group aliens nextmodify the call to update_screen(to give it access to the group of aliens
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 draw(screendraws each alien in the group to the screen creating the fleet now we can create the fleet here' the new function create_fleet()which we place at the end of game_functions py we also need to import the alien classso make sure you add an import statement at the top of the filegame_ functions py --snip-from bullet import bullet from alien import alien --snip-def create_fleet(ai_settingsscreenaliens)"""create full fleet of aliens ""create an alien and find the number of aliens in row spacing between each alien is equal to one alien width alien alien(ai_settingsscreenv alien_width alien rect width available_space_x ai_settings screen_width alien_width number_aliens_x int(available_space_x ( alien_width) create the first row of aliens for alien_number in range(number_aliens_x)create an alien and place it in the row alien alien(ai_settingsscreenalien alien_width alien_width alien_number alien rect alien aliens add(alienwe've already thought through most of this code we need to know the alien' width and height in order to place aliensso we create an alien at before we perform calculations this alien won' be part of the fleetso don' add it to the group aliens at we get the alien' width from its rect attribute and store this value in alien_width so we don' have to keep working through the rect attribute at we calculate the horizontal space available for aliens and the number of aliens that can fit into that space the only change here from our original formulas is that we're using int(to ensure we end up with an integer number of aliens because we don' want to create partial aliensand the range(function needs an aliens
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 right one alien width from the left margin nextwe multiply the alien width by to account for the space each alien takes upincluding the empty space to its rightand we multiply this amount by the alien' position in the row then we add each new alien to the group aliens when you run alien invasionyou should see the first row of aliens appearas in figure - figure - the first row of aliens the first row is offset to the leftwhich is actually good for gameplay because we want the fleet to move right until it hits the edge of the screenthen drop down bitthen move leftand so forth like the classic game space invadersthis movement is more interesting than having the fleet drop straight down we'll continue this motion until all aliens are shot down or until an alien hits the ship or the bottom of the screen note depending on the screen width you've chosenthe alignment of the first row of aliens may look slightly different on your system
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 in row ""available_space_x ai_settings screen_width alien_width number_aliens_x int(available_space_x ( alien_width)return number_aliens_x def create_alien(ai_settingsscreenaliensalien_number)"""create an alien and place it in the row ""alien alien(ai_settingsscreenv alien_width alien rect width alien alien_width alien_width alien_number alien rect alien aliens add(aliendef create_fleet(ai_settingsscreenaliens)"""create full fleet of aliens ""create an alien and find the number of aliens in row alien alien(ai_settingsscreenw number_aliens_x get_number_aliens_x(ai_settingsalien rect widthx create the first row of aliens for alien_number in range(number_aliens_x)create_alien(ai_settingsscreenaliensalien_numberthe body of get_number_aliens_x(is exactly as it was in create_fleet( the body of create_alien(is also unchanged from create_fleet(except that we use the alien that was just created to get the alien width at we replace the code for determining the horizontal spacing with call to get_ number_aliens_x()and we remove the line referring to alien_widthbecause that' now handled inside create_alien(at we call create_alien(this refactoring will make it easier to add new rows and create an entire fleet adding rows to finish the fleetdetermine the number of rows that fit on the screen and then repeat the loop (for creating the aliens in one rowthat number of times to determine the number of rowswe find the available vertical space by subtracting the alien height from the topthe ship height from the bottomand two alien heights from the bottom of the screenavailable_space_y ai_settings screen_height alien_height ship_height aliens
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 adjust until we have reasonable spacing number_rows available_height_y ( alien_heightnow that we know how many rows fit in fleetwe can repeat the code for creating rowgame_ def get_number_rows(ai_settingsship_heightalien_height)functions py """determine the number of rows of aliens that fit on the screen "" available_space_y (ai_settings screen_height ( alien_heightship_heightnumber_rows int(available_space_y ( alien_height)return number_rows def create_alien(ai_settingsscreenaliensalien_numberrow_number)--snip-alien alien_width alien_width alien_number alien rect alien alien rect alien rect height alien rect height row_number aliens add(aliendef create_fleet(ai_settingsscreenshipaliens)--snip-number_aliens_x get_number_aliens_x(ai_settingsalien rect widthnumber_rows get_number_rows(ai_settingsship rect heightalien rect heightx create the fleet of aliens for row_number in range(number_rows)for alien_number in range(number_aliens_x)create_alien(ai_settingsscreenaliensalien_numberrow_numberto calculate the number of rows we can fit on the screenwe write our available_space_y and number_rows calculations into the function get_ number_rows(uwhich is similar to get_number_aliens_x(the calculation is wrapped in parentheses so the outcome can be split over two lineswhich results in lines of characters or less as is recommended we use int(because we don' want to create partial row of aliens to create multiple rowswe use two nested loopsone outer and one inner loop the inner loop creates the aliens in one row the outer loop counts from to the number of rows we wantpython will use the code for making single row and repeat it number_rows times
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()we change an alien' -coordinate value when it' not in the first row by starting with one alien' height to create empty space at the top of the screen each row starts two alien heights below the last rowso we multiply the alien height by two and then by the row number the first row number is so the vertical placement of the first row is unchanged all subsequent rows are placed farther down the screen the definition of create_fleet(also has new parameter for the ship objectwhich means we need to include the ship argument in the call to create_fleet(in alien_invasion pyalien_ invasion py create the fleet of aliens gf create_fleet(ai_settingsscreenshipalienswhen you run the game nowyou should see fleet of aliensas in figure - figure - the full fleet appears in the next sectionwe'll make the fleet movealiens
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 - and using your code in exercise - adjust each star' position by random amount making the fleet move now let' make our fleet of aliens move to the right across the screen until it hits the edgeand then make it drop set amount and move in the other direction we'll continue this movement until all aliens have been shot downone collides with the shipor one reaches the bottom of the screen let' begin by making the fleet move to the right moving the aliens right to move the alienswe'll use an update(method in alien pywhich we'll call for each alien in the group of aliens firstadd setting to control the speed of each aliensettings py def __init__(self)--snip-alien settings self alien_speed_factor thenuse this setting to implement update()alien py def update(self)"""move the alien right ""self +self ai_settings alien_speed_factor self rect self each time we update an alien' positionwe move it to the right by the amount stored in alien_speed_factor we track the alien' exact position with the self attributewhich can hold decimal values we then use the value of self to update the position of the alien' rect
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 have been updatedbecause we'll soon be checking to see whether any bullets hit any aliens finallyadd the new function update_aliens(at the end of the file game_functions pygame_ functions py def update_aliens(aliens)"""update the postions of all aliens in the fleet ""aliens update(we use the update(method on the aliens groupwhich automatically calls each alien' update(method when you run alien invasion nowyou should see the fleet move right and disappear off the side of the screen creating settings for fleet direction now we'll create the settings that will make the fleet move down the screen and to the left when it hits the right edge of the screen here' how to implement this behaviorsettings py alien settings self alien_speed_factor self fleet_drop_speed fleet_direction of represents right- represents left self fleet_direction the setting fleet_drop_speed controls how quickly the fleet drops down the screen each time an alien reaches either edge it' helpful to separate this speed from the alienshorizontal speed so you can adjust the two speeds independently to implement the setting fleet_directionwe could use text valuesuch as 'leftor 'right'but we' end up with ifelif statements testing for the fleet direction insteadbecause we have only two directions to deal withlet' use the values and - and switch between them each time the fleet changes direction (using numbers also makes sense because moving right involves adding to each alien' -coordinate valueand moving left involves subtracting from each alien' -coordinate value aliens
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 left < return true def update(self)"""move the alien right or left ""self +(self ai_settings alien_speed_factor self ai_settings fleet_directionself rect self we can call the new method check_edges(on any alien to see if it' at the left or right edge the alien is at the right edge if the right attribute of its rect is greater than or equal to the right attribute of the screen' rect it' at the left edge if its left value is less than or equal to we modify the method update(to allow motion to the left or right by multiplying the alien' speed factor by the value of fleet_direction if fleet_direction is the value of alien_speed_factor will be added to the alien' current positionmoving the alien to the rightif fleet_direction is - the value will be subtracted from the alien' positionmoving the alien to the left dropping the fleet and changing direction when an alien reaches the edgethe entire fleet needs to drop down and change direction we therefore need to make some substantial changes in game_functions py because that' where we check to see if any aliens are at the left or right edge we'll make this happen by writing the functions check_fleet_edges(and change_fleet_direction()and then modifying update_aliens()game_ functions py def check_fleet_edges(ai_settingsaliens)"""respond appropriately if any aliens have reached an edge "" for alien in aliens sprites()if alien check_edges()change_fleet_direction(ai_settingsaliensbreak
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_settingsaliensaliens update(in check_fleet_edges()we loop through the fleet and call check_edges(on each alien if check_edges(returns truewe know an alien is at an edge and the whole fleet needs to change directionso we call change_fleet_direction(and break out of the loop in change_fleet_direction()we loop through all the aliens and drop each one using the setting fleet_drop_speed vthen we change the value of fleet_direction by multiplying its current value by - we've modified the function update_aliens(to determine whether any aliens are at an edge by calling check_fleet_edges( this function needs an ai_settings parameterso we include an argument for ai_settings in the call to update_aliens()alien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenshipbulletsship update(gf update_bullets(bulletsgf update_aliens(ai_settingsaliensgf update_screen(ai_settingsscreenshipaliensbulletsif you run the game nowthe fleet should move back and forth between the edges of the screen and drop down every time it hits an edge now we can begin shooting down aliens and watch for any aliens that hit the ship or reach the bottom of the screen try it yourse lf - raindropsfind an image of raindrop and create grid of raindrops make the raindrops fall toward the bottom of the screen until they disappear - steady rainmodify your code in exercise - so that when row of raindrops disappears off the bottom of the screena new row appears at the top of the screen and begins to fall aliens
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 members of two groups detecting bullet collisions we want to know right away when bullet hits an alien so we can make an alien disappear as soon as it' hit to do thiswe'll look for collisions immediately after updating bullet' position the sprite groupcollide(method compares each bullet' rect with each alien' rect and returns dictionary containing the bullets and aliens that have collided each key in the dictionary is bulletand the corresponding value is the alien that was hit (we'll use this dictionary when we implement scoring system in use this code to check for collisions in the update_bullets(functiongame_ functions py def update_bullets(aliensbullets)"""update position of bullets and get rid of old bullets ""--snip-check for any bullets that have hit aliens if soget rid of the bullet and the alien collisions pygame sprite groupcollide(bulletsalienstruetruethe new line we added loops through each bullet in the group bullets and then loops through each alien in the group aliens whenever the rects of bullet and alien overlapgroupcollide(adds key-value pair to the dictionary it returns the two true arguments tell pygame whether to delete the bullets and aliens that have collided (to make high-powered bullet that' able to travel to the top of the screendestroying every alien in its pathyou could set the first boolean argument to false and keep the second boolean argument set to true the aliens hit would disappearbut all bullets would stay active until they disappeared off the top of the screen we pass the argument aliens in the call to update_bullets()alien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenshipbulletsship update(gf update_bullets(aliensbulletsgf update_aliens(ai_settingsaliensgf update_screen(ai_settingsscreenshipaliensbullets