id
int64
0
25.6k
text
stringlengths
0
4.59k
0
eric matthes is high school science and math teacher living in alaskawhere he teaches an introductory python course he has been writing programs since he was five years old eric currently focuses on writing software that addresses inefficiencies in education and brings the benefits of open source software to the field ...
1
answer my questions about programmingand for everwho is just beginning to ask me his questions
2
acknowledgments xxvii introduction xxix part ibasics getting started variables and simple data types introducing lists working with lists if statements dictionaries user input and while loops functions classes files and exceptions testing your code part iiprojects project alien invasion ship that fires bullets aliens s...
3
generating data downloading data working with apis project web applications getting started with django user accounts styling and deploying an app afterword appendix ainstalling python appendix btext editors appendix cgetting help appendix dusing git for version control index brief contents
4
acknowledgments xxvii introduction xxix who is this book forxxx what can you expect to learnxxx why pythonxxxi part ibasics getting started setting up your programming environment python and python running snippets of python code hello world python on different operating systems python on linux python on os python on w...
5
exercise - stripping names numbers integers floats avoiding type errors with the str(function integers in python exercise - number eight exercise - favorite number comments how do you write comments what kind of comments should you write exercise - adding comments the zen of python exercise - zen of python summary intr...
6
forgetting to indent forgetting to indent additional lines indenting unnecessarily indenting unnecessarily after the loop forgetting the colon exercise - pizzas exercise - animals making numerical lists using the range(function using range(to make list of numbers simple statistics with list of numbers list comprehensio...
7
boolean expressions exercise - conditional tests exercise - more conditional tests if statements simple if statements if-else statements the if-elif-else chain using multiple elif blocks omitting the else block testing multiple conditions exercise - alien colors # exercise - alien colors # exercise - alien colors # exe...
8
exercise - people exercise - pets exercise - favorite places exercise - favorite numbers exercise - cities exercise - extensions summary user input and while loops how the input(function works writing clear prompts using int(to accept numerical input the modulo operator accepting input in python exercise - rental car e...
9
avoiding argument errors exercise - -shirt exercise - large shirts exercise - cities return values returning simple value making an argument optional returning dictionary using function with while loop exercise - city names exercise - album exercise - user albums passing list modifying list in function preventing funct...
10
the __init__(method for child class inheritance in python defining attributes and methods for the child class overriding methods from the parent class instances as attributes modeling real-world objects exercise - ice cream stand exercise - admin exercise - privileges exercise - battery upgrade importing classes import...
11
handling the filenotfounderror exception analyzing text working with multiple files failing silently deciding which errors to report exercise - addition exercise - addition calculator exercise - cats and dogs exercise - silent cats and dogs exercise - common words storing data using json dump(and json load( saving and ...
12
installing pygame on windows starting the game project creating pygame window and responding to user input setting the background color creating settings class adding the ship image creating the ship class drawing the ship to the screen refactoringthe game_functions module the check_events(function the update_screen(fu...
13
adding rows exercise - stars exercise - better stars making the fleet move moving the aliens right creating settings for fleet direction checking to see whether an alien has hit the edge dropping the fleet and changing direction exercise - raindrops exercise - steady rain shooting aliens detecting bullet collisions mak...
14
displaying the number of ships exercise - all-time high score exercise - refactoring exercise - expanding alien invasion summary project data visualization generating data installing matplotlib on linux on os on windows testing matplotlib the matplotlib gallery plotting simple line graph changing the label type and gra...
15
rolling two dice rolling dice of different sizes exercise - automatic labels exercise - two exercise - three dice exercise - multiplication exercise - practicing with both libraries summary downloading data the csv file format parsing the csv file headers printing the headers and their positions extracting and reading ...
16
working with the response dictionary summarizing the top repositories monitoring api rate limits visualizing repositories using pygal refining pygal charts adding custom tooltips plotting the data adding clickable links to our graph the hacker news api exercise - other languages exercise - active discussions exercise -...
17
exercise - pizzeria pages summary user accounts allowing users to enter data adding new topics adding new entries editing entries exercise - blog setting up user accounts the users app the login page logging out the registration page exercise - blog accounts allowing users to own their data restricting access with @log...
18
using the gunicorn server locally using git to track the project' files pushing to heroku setting up the database on heroku refining the heroku deployment securing the live project committing and pushing changes creating custom error pages ongoing development the secret_key setting deleting project on heroku exercise -...
19
installing idle on linux installing idle on os installing idle on windows customizing idle settings emacs and vim getting help first steps try it again take break refer to this book' resources searching online stack overflow the official python documentation official library documentation /learnpython blog posts irc (i...
20
this book would not have been possible without the wonderful and extremely professional staff at no starch press bill pollock invited me to write an introductory bookand deeply appreciate that original offer tyler ortman helped shape my thinking in the early stages of drafting liz chadwick' and leslie shen' initial fee...
21
every programmer has story about how they learned to write their first program started learning as child when my father was working for digital equipment corporationone of the pioneering companies of the modern computing era wrote my first program on kit computer my dad had assembled in our basement the computer consis...
22
that created and that worked as intended it to that early experience had lasting impact there is real satisfaction in building something with purposesomething that solves problem the software write now meets more significant need than my childhood effortsbut the sense of satisfaction get from creating program that work...
23
extend this concept to more complicated behavior with classesmaking fairly simple programs respond to variety of situations you'll learn to write programs that handle common errors gracefully after working through each of these basic conceptsyou'll write few short programs that solve some well-defined problems finallyy...
24
because of the python communitywhich includes an incredibly diverse and welcoming group of people community is essential to programmers because programming isn' solitary pursuit most of useven the most experienced programmersneed to ask advice from others who have already solved similar problems having well-connected a...
25
ic part of this book teaches you the basic concepts you'll need to write python programs many of these concepts are common to all programming languagesso they'll be useful throughout your life as programmer in you'll install python on your computer and run your first programwhich prints the message hello worldto the sc...
26
objectssuch as dogscatspeoplecarsrocketsand much moreso your code can represent anything real or abstract shows you how to work with files and handle errors so your programs won' crash unexpectedly you'll store data before your program closesand read the data back in when the program runs again you'll learn about pytho...
27
ge ting ta te in this you'll run your first python programhello_world py firstyou'll need to check whether python is installed on your computerif it isn'tyou'll install it you'll also install text editor to work with your python programs text editors recognize python code and highlight sections as you writemaking it ea...
28
todaytwo versions of python are availablepython and the newer python every programming language evolves as new ideas and technologies emergeand the developers of python have continually made the language more versatile and powerful most changes are incremental and hardly noticeablebut in some cases code written for pyt...
29
python is cross-platform programming languagewhich means it runs on all the major operating systems any python program you write should run on any modern computer that has python installed howeverthe methods for setting up python on different operating systems vary slightly in this section you'll learn how to set up py...
30
able to use either version whenever you see the python command in this bookenter python instead most linux distributions have python already installedbut if for some reason yours didn' or if your system came with python and you want to install python refer to appendix installing text editor geany is simple text editori...
31
spaces and capitalization match what is shown here your execute command should look like thispython "%fagainmake sure the spacing and capitalization match what is shown here figure - shows how these commands should look in geany' configuration menu figure - heregeany is configured to use python on linux now run hello_w...
32
you can try running snippets of python code by opening terminal and typing python or python as you did when checking your version do this againbut this time enter the following line in the terminal sessionprint("hello python interpreter!"hello python interpreteryou should see your message printed directly in the curren...
33
you can try running snippets of python code by opening terminal and typing python or python as you did when checking your version do this againbut this time enter the following line in the terminal sessionprint("hello python interpreter!"hello python interpreteryou should see your message printed directly in the curren...
34
when running the currently open file make sure you use the path you found when issuing the command type - python in the previous step save the file as python sublime-build in the default directory that sublime text opens when you choose save running the hello world program to start your first programlaunch sublime text...
35
firstcheck whether python is installed on your system open command window by entering command into the start menu or by holding down the shift key while right-clicking on your desktop and selecting open command window here in the terminal windowenter python in lowercase if you get python prompt ()python is installed on...
36
in terminal session howeveryou may see output that looks more like thisc:\python 'pythonis not recognized as an internal or external commandoperable program or batch file in this case you need to tell windows how to find the python version you just installed your system' python command is usually saved in your driveso ...
37
click releases under the download menuand look for the geany- setup exe installer or something similar run the installer and accept all the defaults to start your first programopen geanypress the windows key and search for geany on your system you should make shortcut by dragging the icon to your taskbar or desktop mak...
38
after you've set these commands correctlyclick ok running the hello world program you should now be able to run your program successfully run hello_world py by selecting build execute in the menuby clicking the execute icon (which shows set of gears)or by pressing terminal window should pop up with the following output...
39
hopefullysetting up your programming environment was successfulbut if you've been unable to run hello_world pyhere are few remedies you can trywhen program contains significant errorpython displays traceback python looks through the file and tries to report the problem the traceback might give you clue as to what issue...
40
most of the programs you write in your text editor you'll run directly from the editorbut sometimes it' useful to run programs from terminal instead for exampleyou might want to run an existing program without opening it for editing you can do this on any system with python installed if you know how to access the direc...
41
pythonyou may need to use the longer version of this commandc:\cd desktop\python_work :\desktop\python_workdir hello_world py :\desktop\python_workc:\python \python hello_world py hello python worldmost of your programs will run fine directly from your editorbut as your work becomes more complexyou might write programs...
42
variables and si in this you'll learn about the different kinds of data you can work with in your python programs you'll also learn how to store your data in variables and how to use those variables in your programs what really happens when you run hello_world py let' take closer look at what python does when you run h...
43
hello python worldwhen you run the file hello_world pythe ending py indicates that the file is python program your editor then runs the file through the python interpreterwhich reads through the program and determines what each word in the program means for examplewhen the interpreter sees the word printit prints to th...
44
hello python worldhello python crash course worldyou can change the value of variable in your program at any timeand python will always keep track of its current value naming and using variables when you're using variables in pythonyou need to adhere to few rules and guidelines breaking some of these rules will cause e...
45
following codeincluding the misspelled word mesage shown in boldmessage "hello python crash course reader!print(mesagewhen an error occurs in your programthe python interpreter does its best to help you figure out where the problem is the interpreter provides traceback when program cannot run successfully traceback is ...
46
the best way to understand new programming concepts is to try using them in your programs if you get stuck while working on an exercise in this booktry doing something else for while if you're still stuckreview the relevant part of that if you still need helpsee the suggestions in appendix try it yourse lf write separa...
47
one of the simplest tasks you can do with strings is change the case of the words in string look at the following codeand try to determine what' happeningname py name "ada lovelaceprint(name title()save this file as name pyand then run it you should see this outputada lovelace in this examplethe lowercase string "ada l...
48
it' often useful to combine strings for exampleyou might want to store first name and last name in separate variablesand then combine them when you want to display someone' full namefirst_name "adalast_name "lovelaceu full_name first_name last_name print(full_namepython uses the plus symbol (+to combine strings in this...
49
in programmingwhitespace refers to any nonprinting charactersuch as spacestabsand end-of-line symbols you can use whitespace to organize your output so it' easier for users to read to add tab to your textuse the character combination \ as shown at uprint("python"python print("\tpython"python to add newline in stringuse...
50
favorite_language 'python favorite_language rstrip('pythonx favorite_language 'python the value stored in favorite_language at contains extra whitespace at the end of the string when you ask python for this value in terminal sessionyou can see the space at the end of the value when the rstrip(method acts on the variabl...
51
one kind of error that you might see with some regularity is syntax error syntax error occurs when python doesn' recognize section of your program as valid python code for exampleif you use an apostrophe within single quotesyou'll produce an error this happens because python interprets everything between the first sing...
52
the print statement has slightly different syntax in python python print "hello python world!hello python worldparentheses are not needed around the phrase you want to print in python technicallyprint is function in python which is why it needs parentheses some python print statements do include parenthesesbut the beha...
53
numbers are used quite often in programming to keep score in gamesrepresent data in visualizationsstore information in web applicationsand so on python treats numbers in several different waysdepending on how they are being used let' first look at how python manages integersbecause they are the simplest to work with in...
54
behave appropriately no matter where the decimal point appears for the most partyou can use decimals without worrying about how they behave simply enter the numbers you want to useand python will most likely do what you expect but be aware that you can sometimes get an arbitrary number of decimal places in your answer ...
55
value or the characters and when you use integers within strings like thisyou need to specify explicitly that you want python to use the integer as string of characters you can do this by wrapping the variable in the str(functionwhich tells python to represent non-string values as stringsage message "happy str(age"rd b...
56
- number eightwrite additionsubtractionmultiplicationand division operations that each result in the number be sure to enclose your operations in print statements to see the results you should create four lines that look like thisprint( your output should simply be four lines with the number appearing once on each line...
57
other programmersyou should write meaningful comments todaymost software is written collaborativelywhether by group of employees at one company or group of people working together on an open source project skilled programmers expect to see comments in codeso it' best to start adding descriptive comments to your program...
58
should be important to you as beginning python programmer import this the zen of pythonby tim peters beautiful is better than ugly python programmers embrace the notion that code can be beautiful and elegant in programmingpeople solve problems programmers have always respected well-designedefficientand even beautiful s...
59
involved topicstry to keep this philosophy of simplicity and clarity in mind experienced programmers will respect your code more and will be happy to give you feedback and collaborate with you on interesting projects try it yourse lf - zen of pythonenter import this into python terminal session and skim through the add...
60
ci li in this and the next you'll learn what lists are and how to start working with the elements in list lists allow you to store sets of information in one placewhether you have just few items or millions of items lists are one of python' most powerful features readily accessible to new programmersand they tie togeth...
61
list usually contains more than one elementit' good idea to make the name of your list pluralsuch as lettersdigitsor names in pythonsquare brackets ([]indicate listand individual elements in the list are separated by commas here' simple example of list that contains few kinds of bicyclesbicycles py bicycles ['trek''can...
62
python considers the first item in list to be at position not position this is true of most programming languagesand the reason has to do with how the list operations are implemented at lower level if you're receiving unexpected resultsdetermine whether you are making simple off-by-one error the second item in list has...
63
the variable message the output is simple sentence about the first bicycle in the listmy first bicycle was trek try it yourse lf try these short programs to get some firsthand experience with python' lists you might want to create new folder for each exercises to keep them organized - namesstore the names of few of you...
64
the list is 'hondahow would we change the value of this first itemmotorcycles py motorcycles ['honda''yamaha''suzuki'print(motorcyclesv motorcycles[ 'ducatiprint(motorcyclesthe code at defines the original listwith 'hondaas the first element the code at changes the value of the first item to 'ducatithe output shows tha...
65
exampleyou can start with an empty list and then add items to the list using series of append(statements using an empty listlet' add the elements 'honda''yamaha'and 'suzukito the listmotorcycles [motorcycles append('honda'motorcycles append('yamaha'motorcycles append('suzuki'print(motorcyclesthe resulting list looks ex...
66
want to remove that user from the list of active users you can remove an item according to its position in the list or according to its value removing an item using the del statement if you know the position of the item you want to remove from listyou can use the del statement motorcycles ['honda''yamaha''suzuki'print(...
67
motorcycles ['honda''yamaha''suzuki'print(motorcyclesv popped_motorcycle motorcycles pop( print(motorcyclesx print(popped_motorcyclewe start by defining and printing the list motorcycles at at we pop value from the list and store that value in the variable popped_motorcycle we print the list at to show that value has b...
68
print message about that motorcycle at the output is simple sentence describing the first motorcycle ever ownedthe first motorcycle owned was honda remember that each time you use pop()the item you work with is no longer stored in the list if you're unsure whether to use the del statement or the pop(methodhere' simple ...
69
the list but is still stored in the variable too_expensiveallowing us to print statement about why we removed 'ducatifrom the list of motorcycles['honda''yamaha''suzuki''ducati'['honda''yamaha''suzuki' ducati is too expensive for me note the remove(method deletes only the first occurrence of the value you specify if th...
70
arrive in time for the dinnerand you have space for only two guests start with your program from exercise - add new line that prints message saying that you can invite only two people for dinner use pop(to remove guests from your list one at time until only two names remain in your list each time you pop name from your...
71
argument reverse=true to the sort(method the following example sorts the list of cars in reverse alphabetical ordercars ['bmw''audi''toyota''subaru'cars sort(reverse=trueprint(carsagainthe order of the list is permanently changed['toyota''subaru''bmw''audi'sorting list temporarily with the sorted(function to maintain t...
72
sorting list alphabetically is bit more complicated when all the values are not in lowercase there are several ways to interpret capital letters when you're deciding on sort orderand specifying the exact order can be more complex than we want to deal with at this time howevermost approaches to sorting will build direct...
73
- seeing the worldthink of at least five places in the world you' like to visit store the locations in list make sure the list is not in alphabetical order print your list in its original order don' worry about printing the list neatlyjust print it as raw python list use sorted(to print your list in alphabetical order ...
74
traceback (most recent call last)file "motorcycles py"line in print(motorcycles[ ]indexerrorlist index out of range python attempts to give you the item at index but when it searches the listno item in motorcycles has an index of because of the off-by-one nature of indexing in liststhis error is typical people think th...
75
- intentional errorif you haven' received an index error in one of your programs yettry to make one happen change an index in one of your programs to produce an index error make sure you correct the error before closing the program summary in this you learned what lists are and how to work with the individual items in ...
76
li in you learned how to make simple listand you learned to work with the individual elements in list in this you'll learn how to loop through an entire list using just few lines of code regardless of how long the list is looping allows you to take the same actionor set of actionswith every item in list as resultyou'll...
77
each name in the list we could do this by retrieving each name from the list individuallybut this approach could cause several problems for oneit would be repetitive to do this with long list of names alsowe' have to change our code each time the list' length changed for loop avoids both of these issues by letting pyth...
78
python repeats the entire loop once more with the last value in the list'carolinabecause no more values are in the listpython moves on to the next line in the program in this case nothing comes after the for loopso the program simply ends when you're using loops for the first timekeep in mind that the set of steps is r...
79
each value in the list let' add second line to our messagetelling each magician that we're looking forward to their next trickmagicians ['alice''david''carolina'for magician in magiciansprint(magician title("that was great trick!" print(" can' wait to see your next trickmagician title(\ "because we have indented both p...
80
the listas you saw earlier howeverbecause the line at is not indentedit' printed only oncealicethat was great tricki can' wait to see your next trickalice davidthat was great tricki can' wait to see your next trickdavid carolinathat was great tricki can' wait to see your next trickcarolina thank youeveryone that was gr...
81
expects an indented block and doesn' find oneit lets you know which line it had problem with file "magicians py"line print(magicianindentationerrorexpected an indented block you can usually resolve this kind of indentation error by indenting the line or lines immediately after the for statement forgetting to indent add...
82
if you accidentally indent line that doesn' need to be indentedpython informs you about the unexpected indenthello_world py message "hello python world!print(messagewe don' need to indent the print statement at ubecause it doesn' belong to the line above ithencepython reports that errorfile "hello_world py"line print(m...
83
additional lineson page because python doesn' know what you're trying to accomplish with your codeit will run all code that is written in valid syntax if an action is repeated many times when it should be executed only oncedetermine whether you just need to unindent the code for that action forgetting the colon the col...
84
many reasons exist to store set of numbers for exampleyou'll need to keep track of the positions of each character in gameand you might want to keep track of player' high scores as well in data visualizationsyou'll almost always work with sets of numberssuch as temperaturesdistancespopulation sizesor latitude and longi...
85
range()try adjusting your end value by using range(to make list of numbers if you want to make list of numbersyou can convert the results of range(directly into list using the list(function when you wrap list(around call to the range(functionthe output will be list of numbers in the example in the previous sectionwe si...
86
squares finallywhen the loop has finished runningthe list of squares is printed at [ to write this code more conciselyomit the temporary variable square and append each new value directly to the listsquares [for value in range( , ) squares append(value** print(squaresthe code at does the same work as the lines at and i...
87
earlier but uses list comprehensionsquares py squares [value** for value in range( , )print(squaresto use this syntaxbegin with descriptive name for the listsuch as squares nextopen set of square brackets and define the expression for the values you want to store in the new list in this example the expression is value*...
88
in you learned how to access single elements in listand in this you've been learning how to work through all the elements in list you can also work with specific group of items in listwhich python calls slice slicing list to make sliceyou specify the index of the first and last elements you want to work with as with th...
89
for exampleif you want all items from the third item through the last itemyou can start with index and omit the second indexplayers ['charles''martina''michael''florence''eli'print(players[ :]python returns all items from the third item through the end of the list['michael''florence''eli'this syntax allows you to outpu...
90
an appropriate amount of information on each page copying list oftenyou'll want to start with an existing list and make an entirely new list based on the first one let' explore how copying list works and examine one situation in which copying list is useful to copy listyou can make slice that includes the entire origin...
91
print(friend_foodsat we copy the original items in my_foods to the new list friend_foodsas we did in the previous example nextwe add new food to each listat we add 'cannolito my_foodsand at we add 'ice creamto friend_foods we then print the two lists to see whether each of these foods is in the appropriate list my favo...
92
don' worry about the details in this example for now basicallyif you're trying to work with copy of list and you see unexpected behaviormake sure you are copying the list using sliceas we did in the first example try it yourse lf - slicesusing one of the programs you wrote in this add several lines to the end of the pr...
93
we can ensure that its size doesn' change by putting the dimensions into tupledimensions py dimensions ( print(dimensions[ ]print(dimensions[ ]we define the tuple dimensions at uusing parentheses instead of square brackets at we print each element in the tuple individuallyusing the same syntax we've been using to acces...
94
although you can' modify tupleyou can assign new value to variable that holds tuple so if we wanted to change our dimensionswe could redefine the entire tupleu dimensions ( print("original dimensions:"for dimension in dimensionsprint(dimensionv dimensions ( print("\nmodified dimensions:"for dimension in dimensionsprint...
95
now that you're writing longer programsideas about how to style your code are worthwhile to know take the time to make your code as easy as possible to read writing easy-to-read code helps you keep track of what your programs are doing and helps others understand your code as well python programmers have agreed on numb...
96
many python programmers recommend that each line should be less than characters historicallythis guideline developed because most computers could fit only characters on single line in terminal window currentlypeople can fit much longer lines on their screensbut other reasons exist to adhere to the -character standard l...
97
- pep look through the original pep style guide at dev/peps/pep- you won' use much of it nowbut it might be interesting to skim through it - code reviewchoose three of the programs you've written in this and modify each one to comply with pep use four spaces for each indentation level set your text editor to insert fou...
98
if tat me programming often involves examining set of conditions and deciding which action to take based on those conditions python' if statement allows you to examine the current state of program and respond appropriately to that state in this you'll learn to write conditional testswhich allow you to check any conditi...
99
the following short example shows how if tests let you respond to special situations correctly imagine you have list of cars and you want to print out the name of each car car names are proper namesso the names of most cars should be printed in title case howeverthe value 'bmwshould be printed in all uppercase the foll...