id
int64
0
25.6k
text
stringlengths
0
4.59k
6,600
using web services codethe program takes the search string and constructs url with the search string as properly encoded parameter and then uses urllib to retrieve the text from the google geocoding api unlike fixed web pagethe data we get depends on the parameters we send and the geographical data stored in google' se...
6,601
"types""country""political]"formatted_address""ann arbormiusa""geometry""bounds""northeast""lat" "lng"- }"southwest""lat" "lng"- }"location""lat" "lng"- }"location_type""approximate""viewport""northeast""lat" "lng"- }"southwest""lat" "lng"- }"place_id""chijmx wpigr rxihkb cds""types""locality""political]"status""oklat ...
6,602
using web services exercise change either geojson py or geoxml py to print out the twocharacter country code from the retrieved data add error checking so your program does not traceback if the country code is not there once you have it workingsearch for "atlantic oceanand make sure it can handle locations that are not...
6,603
for the programs we run with twitterwe hide all the complexity in the files oauth py and twurl py we simply set the secrets in hidden py and then send the desired url to the twurl augment(function and the library code adds all the necessary parameters to the url for us this program retrieves the timeline for particular...
6,604
using web services retrieving [{"created_at":"sat sep : : + ""id": ,"id_str":" ""text":" months after my freak bocce ball accidentmy wedding ring fits again:)\ \nhttps:\/\/ co\/ xmhpx kgx""source":"web","truncated":falseremaining enter twitter accountalong with the returned timeline datatwitter also returns metadata ab...
6,605
for in js['users']print( ['screen_name']if 'statusnot in uno status found'print(continue ['status']['text'print(' [: ]codesince the json becomes set of nested python lists and dictionarieswe can use combination of the index operation and for loops to wander through the returned data structures with very little python c...
6,606
using web services leahculver @jazzychad just bought one __ _valeriei rt @wsjbig employers like googleat& are ericbollens rt @lukewsneak peekmy long take on the good & halherzog learning objects is we had cake with the loscweeker @devicelabdc love itnow where so get that "etc enter twitter accountthe last bit of th...
6,607
object-oriented programming managing larger programs at the beginning of this bookwe came up with four basic programming patterns which we use to construct programssequential code conditional code (if statementsrepetitive code (loopsstore and reuse (functionsin later we explored simple variables as well as collection d...
6,608
object-oriented programming getting started like many aspects of programmingit is necessary to learn the concepts of object oriented programming before you can use them effectively you should approach this as way to learn some terms and concepts and work through few simple examples to lay foundation for future learning...
6,609
the last three lines of the program are equivalentbut it is more convenient to simply use the square bracket syntax to look up an item at particular position in list we can take look at the capabilities of an object by looking at the output of the dir(functionstuff list(dir(stuff['__add__''__class__''__contains__''__de...
6,610
object-oriented programming program input output figure program to run thisdownload the beautifulsoup zip file and unzip it in the same directory as this file import urllib requesturllib parseurllib error from bs import beautifulsoup import ssl ignore ssl certificate errors ctx ssl create_default_context(ctx check_host...
6,611
string object input urllib object socket object dictionary object string object output beautifulsoup object html parser object figure program as network of objects program was "orchestrating the movement of data between objects it was just lines of code that got the job done subdividing problem one of the advantages of...
6,612
object-oriented programming string object input urllib object socket object dictionary object string object output beautifulsoup object html parser object figure ignoring detail when building an object an object can contain number of functions (which we call methodsas well as data that is used by those functions we cal...
6,613
figure class and two objects an partyanimal(this is where we instruct python to construct ( createan object or instance of the class partyanimal it looks like function call to the class itself python constructs the object with the right data and methods and returns the object which is then assigned to the variable an i...
6,614
object-oriented programming in this variationwe access the code from within the class and explicitly pass the object pointer an as the first parameter ( self within the methodyou can think of an party(as shorthand for the above line when the program executesit produces the following outputso far so far so far so far th...
6,615
object lifecycle in the previous exampleswe define class (template)use that class to create an instance of that class (object)and then use the instance when the program finishesall of the variables are discarded usuallywe don' think much about the creation and destruction of variablesbut often as our objects become mor...
6,616
object-oriented programming when developing objectsit is quite common to add constructor to an object to set up initial values for the object it is relatively rare to need destructor for an object multiple instances so farwe have defined classconstructed single objectused that objectand then thrown the object away howe...
6,617
sally constructed jim constructed sally party count jim party count sally party count inheritance another powerful feature of object-oriented programming is the ability to create new class by extending an existing class when extending classwe call the original class the parent class and the new class the child class fo...
6,618
object-oriented programming in the dir output for the object (instance of the cricketfan class)we see that it has the attributes and methods of the parent classas well as the attributes and methods that were added when the class was extended to create the cricketfan class summary this is very quick introduction to obje...
6,619
glossary attribute variable that is part of class class template that can be used to construct an object defines the attributes and methods that will make up the object child class new class created when parent class is extended the child class inherits all of the attributes and methods of the parent class constructor ...
6,620
object-oriented programming
6,621
using databases and sql what is databasea database is file that is organized for storing data most databases are organized like dictionary in the sense that they map from keys to values the biggest difference is that the database is on disk (or other permanent storage)so it persists after the program ends because datab...
6,622
using databases and sql column attribute table relation row tuple figure relational databases database browser for sqlite while this will focus on using python to work with data in sqlite database filesmany operations can be done more conveniently using software called the database browser for sqlite which is freely av...
6,623
the code to create database file and table named tracks with two columns in the database is as followsimport sqlite conn sqlite connect('music sqlite'cur conn cursor(cur execute('drop table if exists tracks'cur execute('create table tracks (title textplays integer)'conn close(codethe connect operation makes "connection...
6,624
using databases and sql command that we are adding (such as the table and column nameswill be shown in lowercase the first sql command removes the tracks table from the database if it exists this pattern is simply to allow us to run the same program to create the tracks table over and over again without causing an erro...
6,625
tracks title plays thunderstruck my way figure rows in table first we insert two rows into our table and use commit(to force the data to be written to the database file then we use the select command to retrieve the rows we just inserted from the table on the select commandwe indicate which columns we would like (title...
6,626
using databases and sql since there are so many different database vendorsthe structured query language (sqlwas standardized so we could communicate in portable manner to database systems from multiple vendors relational database is made up of tablesrowsand columns the columns generally have type such as textnumericor ...
6,627
spidering twitter using database in this sectionwe will create simple spidering program that will go through twitter accounts and build database of them notebe very careful when running this program you do not want to pull too much data or run the program for too long and end up having your twitter access shut off one ...
6,628
using databases and sql while trueacct input('enter twitter accountor quit'if (acct ='quit')break if (len(acct )cur execute('select name from twitter where retrieved limit 'tryacct cur fetchone()[ exceptprint('no unretrieved twitter accounts found'continue url twurl augment(twitter_url{'screen_name'acct'count'' '}print...
6,629
in the main loop of the programwe prompt the user for twitter account name or "quitto exit the program if the user enters twitter accountwe retrieve the list of friends and statuses for that user and add each friend to the database if not already in the database if the friend is already in the listwe add to the friends...
6,630
using databases and sql so the first time the program runs and we enter twitter accountthe program runs as followsenter twitter accountor quitdrchuck retrieving new accounts revisited enter twitter accountor quitquit since this is the first time we have run the programthe database is empty and we create the database in...
6,631
enter twitter accountor quitretrieving new accounts revisited enter twitter accountor quitretrieving new accounts revisited enter twitter accountor quitquit since we pressed enter ( we did not specify twitter account)the following code is executedif len(acct cur execute('select name from twitter where retrieved limit '...
6,632
using databases and sql ('kthanos' ('lecturetools' rows we can see that we have properly recorded that we have visited lhawthorn and opencontent also the accounts cnxorg and kthanos already have two followers since we now have retrieved the friends of three people (drchuckopencontentand lhawthornour table has rows of f...
6,633
this duplication of string data violates one of the best practices for database normalization which basically states that we should never put the same string data in the database more than once if we need the data more than oncewe create numeric key for the data and reference the actual data using this key in practical...
6,634
using databases and sql people follows from_id to_id id name retrieved drchuck opencontent lhawthorn steve_coppin figure relationships between tables import urllib requesturllib parseurllib error import twurl import json import sqlite import ssl twitter_url 'conn sqlite connect('friends sqlite'cur conn cursor(cur execu...
6,635
exceptprint('no unretrieved twitter accounts found'continue elsecur execute('select id from people where name limit '(acct)tryid cur fetchone()[ exceptcur execute('''insert or ignore into people (nameretrievedvalues (? )'''(acct)conn commit(if cur rowcount ! print('error inserting account:'acctcontinue id cur lastrowid...
6,636
using databases and sql print(friendcur execute('select id from people where name limit '(friend)tryfriend_id cur fetchone()[ countold countold exceptcur execute('''insert or ignore into people (nameretrievedvalues (? )'''(friend)conn commit(if cur rowcount ! print('error inserting account:'friendcontinue friend_id cur...
6,637
we indicate that the name column in the people table must be unique we also indicate that the combination of the two numbers in each row of the follows table must be unique these constraints keep us from making mistakes such as adding the same relationship more than once we can take advantage of these constraints in th...
6,638
using databases and sql friend_id cur fetchone()[ countold countold exceptcur execute('''insert or ignore into people (nameretrievedvalues ? )'''friendconn commit(if cur rowcount ! print('error inserting account:',friendcontinue friend_id cur lastrowid countnew countnew if we end up in the except codeit simply means th...
6,639
we started with the drchuck account and then let the program automatically pick the next two accounts to retrieve and add to our database the following is the first few rows in the people and follows tables after this run is completedpeople( 'drchuck' ( 'opencontent' ( 'lhawthorn' ( 'steve_coppin' ( 'davidkocher' rows ...
6,640
using databases and sql foreign key is usually number that points to the primary key of an associated row in different table an example of foreign key in our data model is the from_id we are using naming convention of always calling the primary key field name id and appending the suffix _id to any field name that is fo...
6,641
the result of the join is to create extra-long "metarowswhich have both the fields from people and the matching fields from follows where there is more than one match between the id field from people and the from_id from peoplethen join creates metarow for each of the matching pairs of rowsduplicating data as needed th...
6,642
using databases and sql ( 'drchuck' ( 'opencontent' ( 'lhawthorn' ( 'steve_coppin' ( 'davidkocher' rows follows( ( ( ( ( rows connections for id= ( 'drchuck' ( 'cnxorg' ( 'kthanos' ( 'somethinggirl' ( 'ja_pac' rows you see the columns from the people and follows tables and the last set of rows is the result of the sele...
6,643
debugging one common pattern when you are developing python program to connect to an sqlite database will be to run python program and check the results using the database browser for sqlite the browser allows you to quickly check to see if your program is working properly you must be careful because sqlite takes care ...
6,644
using databases and sql
6,645
visualizing data so far we have been learning the python language and then learning how to use pythonthe networkand databases to manipulate data in this we take look at three complete applications that bring all of these things together to manage and visualize data you might use these applications as sample code to hel...
6,646
visualizing data figure an openstreetmap data for the locationit will call the geocoding api to retrieve the data and store it in the database here is sample run after there is already some data in the databasefound in database agh university of science and technology found in database academy of fine arts warsaw polan...
6,647
the geoload py program can be stopped at any timeand there is counter that you can use to limit the number of calls to the geocoding api for each run given that the where data only has few hundred data itemsyou should not run into the daily rate limitbut if you had more data it might take several runs over several days...
6,648
visualizing data google page rank algorithm to determine which pages are most highly connectedand then visualize the page rank and connectivity of our small corner of the web we will use the javascript visualization library visualization output you can download and extract this application fromwww py com/code /pagerank...
6,649
how many pagesyou can have multiple starting points in the same database--within the programthese are called "websthe spider chooses randomly amongst all non-visited links across all the webs as the next page to spider if you want to dump the contents of the spider sqlite fileyou can run spdump py as follows( none '( n...
6,650
visualizing data - - - - - - - - [( )( )( )( )( )for each iteration of the page rank algorithm it prints the average change in page rank per page the network initially is quite unbalanced and so the individual page rank values change wildly between iterations but in few short iterationsthe page rank converges you shoul...
6,651
figure word cloud from the sakai developer list we will be using data from free email list archiving service called this service is very popular with open source projects because it provides nice searchable archive of their email activity they also have very liberal policy regarding accessing their data through their a...
6,652
visualizing data as needed it may take many hours to pull all the data down so you may need to restart several times here is run of gmane py retrieving the last five messages of the sakai developer listhow many messages: nealcaidin@sakaifoundation org re[building samuelgutierrezjimenez@gmail com re[building da @vt edu ...
6,653
: : - : ggolden @mac com : : - : tpamsler@ucdavis edu : : - : lance@indiana edu : : - : vrajgopalan@ucmerced edu the gmodel py program handles number of data cleaning tasks domain names are truncated to two levels for comorgeduand net other domain names are truncated to three levels so si umich edu becomes umich edu an...
6,654
visualizing data how many to dump loaded messages subjects senders top email list participants steve swinsburg@gmail com azeckoski@unicon net ieb@tfd co uk csev@umich edu david horwitz@uct ac za top email list organizations gmail com umich edu uct ac za indiana edu unicon net note how much more quickly gbasic py runs c...
6,655
figure sakai mail activity by organization
6,656
visualizing data
6,657
contributions contributor list for python for everybody andrzej wojtowiczelliott hauserstephen cattosue blumenbergtamara brunnockmihaela mackchris kolosiwskydustin farleyjens leerssennaveen ktmirza ibrahimovicnaveen (@togarnk)zhou fangyialistair walsherica brodyjih-sheng huanglouis luangkesornand michael fudge you can ...
6,658
appendix contributions the class was too high andeven for students who succeededthe overall level of achievement was too low one of the problems saw was the books they were too bigwith too much unnecessary detail about javaand not enough high-level guidance about how to program and they all suffered from the trap door ...
6,659
acknowledgements for "think python(allen downeyfirst and most importantlyi thank jeff elknerwho translated my java book into pythonwhich got this project started and introduced me to what has turned out to be my favorite language also thank chris meyerswho contributed several sections to how to think like computer scie...
6,660
appendix contributions lin peihengray hagtvedttorsten hubschinga petuhhovarne babenhauserheidemark casidascott tylergordon shephardandrew turneradam hobartdaryl hammond and sarah zimmermangeorge sassbrian binghamleah engelbert-fentonjoe funkechao-chao chenjeff painelubos pintesgregg lind and abigail heithoffmax hailper...
6,661
copyright detail this work is licensed under creative common attribution-noncommercialsharealike unported license this license is available at creativecommons org/licenses/by-nc-sa/ would have preferred to license the book under the less restrictive cc-by-sa license but unfortunately there are few unscrupulous organiza...
6,662
appendix copyright detail granted as long as there is clear added value or benefit to students or teachers that will accrue as result of the new work charles severance www dr-chuck com ann arbormiusa september
6,663
access accumulator sum algorithm aliasing copying to avoid alternative execution and operator api key append method argument keyword list optional arithmetic operator assignment item tuple assignment statement attribute beautifulsoup binary file bisectiondebugging by body bool type boolean expression boolean operator b...
6,664
counter counting and looping cpu creative commons licenseiv curl cursor cursor function index empty string encapsulation end of line character equivalence equivalent error runtime semantic data structure shape database syntax indexes error message database browser evaluate database normalization exception debugging ind...
6,665
all rights reserved no part of this work may be reproduced or transmitted in any form or by any meanselectronic or mechanicalincluding photocopyingrecordingor by any information storage or retrieval systemwithout the prior written permission of the copyright owner and the publisher isbn- - - (printisbn- - - (ebookpubli...
6,666
al sweigart is software developerauthorand fellow of the python software foundation he was previously the education director at oaklandcalifornia' video game museumthe museum of art and digital enter tainment he has written several programming booksincluding automate the boring stuff with python and invent your own com...
6,667
introduction xv project bagelsdeduce secret three-digit number based on clues practice using constants project birthday paradoxdetermine the probability that two people share the same birthday in groups of different sizes use python' datetime module project bitmap messagedisplay message on the screen configured by bitm...
6,668
generator for your content farm practice string manipulation and text generation project collatz sequenceexplore the simplest impossible conjecture in mathematics learn about the modulus operator project conway' game of lifethe classic cellular automata whose simple rules produce complex emergent behavior use dictionar...
6,669
work with screen coordinates and relative directional movements project factor finderfind all the multiplicative factors of number use the modulus operator and python' math module project fast drawtest your reflexes to see if you're the fastest keyboard in the west learn about the keyboard buffer project fibonaccigener...
6,670
simulate gravity and use collision detection project hungry robotsavoid killer robots in maze create simple ai for robot movements project 'accuse! detective game to determine liars and truth-tellers use data structures to generate relationships between suspectsplacesand item clues project langton' anta cellular automa...
6,671
table up to practice spacing text project ninety-nine bottlesdisplay the lyrics to repetitive song use loops and string templates to produce text project ninety-nniine boottelsdisplay the lyrics to repetitive song that get more distorted with each verse manipulate strings to introduce distortions project numeral system...
6,672
and decrypting text convert between letters and numbers to perform math on text project rotating cubea rotating cube animation learn rotation and line drawing algorithms project royal game of ura , -year-old game from mesopotamia use ascii art and string templates to draw board game project seven-segment display module...
6,673
deduction puzzle model puzzle with data structure project text-to-speech talkermake your computer talk to you use your operating system' text-to-speech engine project three-card montethe tricky fast-swapping card game that scammers play on tourists manipulate data structure based on random movements project tic-tac-toe...
6,674
programming was so easy when it was just following print('helloworld!'tutorials perhaps you've followed well-structured book or online course for beginnersworked through the exercisesand nodded along with its technical jargon that you (mostlyunderstood howeverwhen it came time to leave the nest to write your own progra...
6,675
concepts are appliedwith collection of over gamessimulationsand digital art programs these aren' code snippetsthey're fullrunnable python programs you can copy their code to become familiar with how they workexperiment with your own changesand then attempt to re-create them on your own as practice after whileyou'll sta...
6,676
that programming hasn' "clickedfor them they may be able to solve the practice exercises from their tutorials but still struggle to picture what complete program "looks like by first copying and then later re-creating the games in this bookthey'll be exposed to how the programming concepts they've learned are assembled...
6,677
manually typing it yourself (don' use copy and paste! run the program againand go back and fix any typos or bugs you may have introduced run the program under debuggerso you can carefully execute each line of code one at time to understand what it does find the comments marked with (!to find code that you can modify an...
6,678
pythonyou can find more instructions at downloading and installing the mu editor while the python software runs your programyou'll type the python code into text editor or integrated development environment (ideapplication recommend using mu editor for your ide if you are beginner because it' simple and doesn' distract...
6,679
on macosopen the finder window and click applications python idle on ubuntuselect applicationsaccessoriesterminal and then enter idle (you may also be able to click applications at the top of the screenselect programmingand then click idle on the raspberry piclick the raspberry pi menu button in the top-left cornerthen...
6,680
or import bext to check if the installation worked if these import instruction don' produce an error messagethese modules installed correctly and you'll be able to run the projects in this book that use these modules copying the code from this book programming is skill that you improve by programming don' just read the...
6,681
:\users\althento run python programsenter python yourprogram py on windows or python yourprogram py on macos and linuxreplacing yourprogram py with the name of your python programc:\users\al>python guess py guess the numberby al sweigart al@inventwithpython com am thinking of number between and you have guesses left ta...
6,682
software developers search the internet on daily basis in this sectionyou'll learn how to ask smart questions and search for answers on the internet when your program tries to carry out an invalid instructionit displays an error message called traceback the traceback tells you what kind of error occurred and which line...
6,683
it does not mean pressing the ctrl key oncefollowed by pressing the key you can discover the common shortcutssuch as ctrl- to save and ctrl- to copyby using the mouse to open the menu bar at the top of the application (in windows and linuxor top of the screen (in macosit' well worth the time to learn and use these keyb...
6,684
window to enter word to find in the program often the key will repeat this search to highlight the next occurrence of the word this feature can save you an extraordinary amount of time compared to manually scrolling through your document to find word editors also have find-and-replace featurewhich is often assigned the...
6,685
the values currently stored in the program' variables are displayed somewhere in the debugging window in every debugger howeverone common method of debugging your programs is print debuggingadding print(calls to display the values of variables and then rerunning your program while simple and convenientthis approach to ...
6,686
bagel in bagelsa deductive logic gameyou must guess secret three-digit number based on clues the game offers one of the following hints in response to your guess"picowhen your guess has correct digit in the wrong place"fermiwhen your guess has correct digit in the correct placeand "bagelsif your guess has no correct di...
6,687
when you run bagels pythe output will look like thisbagelsa deductive logic game by al sweigart al@inventwithpython com am thinking of -digit number try to guess what it is here are some clueswhen saythat meanspico one digit is correct but in the wrong position fermi one digit is correct and in the right position bagel...
6,688
max_guesses (!try setting this to or def main() print('''bagelsa deductive logic game by al sweigart al@inventwithpython com am thinking of {}-digit number with no repeated digits try to guess what it is here are some clues when saythat means pico one digit is correct but in the wrong position fermi one digit is correc...
6,689
secretnum ' for in range(num_digits) secretnum +str(numbers[ ] return secretnum def getclues(guesssecretnum) """returns string with the picofermibagels clues for guess and secret number pair "" if guess =secretnum return 'you got it! clues [ for in range(len(guess)) if guess[ =secretnum[ ] correct digit is in the corre...
6,690
what happens if you set num_digits to number larger than what happens if you replace secretnum getsecretnum(on line with secretnum ' ' what error message do you get if you delete or comment out numguesses on line what happens if you delete or comment out random shuffle(numberson line what happens if you delete or comme...
6,691
ay the birthday paradoxalso called the birthday problemis the surprisingly high probability that two people will have the same birthday even in small group of people in group of peoplethere' percent chance of two people having matching birthday but even in group as small as peoplethere' percent chance of matching birth...
6,692
when you run birthdayparadox pythe output will look like thisbirthday paradoxby al sweigart al@inventwithpython com --snip-how many birthdays shall generate(max here are birthdaysoct sep may jul feb jan aug feb dec jan may sep oct may may oct dec jun jul dec nov aug mar in this simulationmultiple people have birthday o...
6,693
for in range(numberofbirthdays) the year is unimportant for our simulationas long as all birthdays have the same year startofyear datetime date( get random day into the year randomnumberofdays datetime timedelta(random randint( ) birthday startofyear randomnumberofdays birthdays append(birthday return birthdays def get...
6,694
monthname months[birthday month datetext '{{}format(monthnamebirthday day print(datetextend='' print( print( determine if there are two birthdays that match match getmatch(birthdays display the results print('in this simulation'end='' if match !none monthname months[match month datetext '{{}format(monthnamematch day pr...
6,695
int(responseon line how can you make the program display full month namessuch as 'januaryinstead of 'jan' how could you make ' simulations run appear every , simulations instead of every , project #
6,696
bitmap message this program uses multiline string as bitmapa image with only two possible colors for each pixelto determine how it should display message from the user in this bitmapspace characters represent an empty spaceand all other characters are replaced by characters in the user' message the provided bitmap rese...
6,697
when you run bitmapmessage pythe output will look like thisbitmap messageby al sweigart al@inventwithpython com enter the message to display with the bitmap hellohello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!he lo!hello!hello !he lo llo!hello!hello!hello!hello!he llo!hello!hello!hello he lo !hello!h...
6,698
import sys (!try changing this multiline string to any image you like there are periods along the top and bottom of this string (you can also copy and paste this string from bitmap "" ********************************************* *************************************************** **************************************...
6,699
try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if the player enters blank string for the message does it matter what the nonspace characters are in the bitmap variable' string what does the variable...