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' servers once we retrieve the json datawe parse it with the json library and do few checks to make sure that we received good datathen extract the information that we are looking for the output of the program is as follows (some of the returned json has been removed)python geojson py enter locationann arbormi retrieving retrieved characters "results""address_components""long_name""ann arbor""short_name""ann arbor""types""locality""political}"long_name""washtenaw county""short_name""washtenaw county""types""administrative_area_level_ ""political}"long_name""michigan""short_name""mi""types""administrative_area_level_ ""political}"long_name""united states""short_name""us" |
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 lng - ann arbormiusa enter locationyou can download www py com/code /geoxml py to explore the xml variant of the google geocoding api |
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 in any country application twitter as the twitter api became increasingly valuabletwitter went from an open and public api to an api that required the use of oauth signatures on each api request for this next sample programdownload the files twurl pyhidden pyoauth pyand twitter py from www py com/code and put them all in folder on your computer to make use of these programs you will need to have twitter accountand authorize your python code as an applicationset up keysecrettoken and token secret you will edit the file hidden py and put these four strings into the appropriate variables in the filekeep this file separate create new app and get the four strings def oauth()return {"consumer_key"" lu ng""consumer_secret"dnkenac new mmn ""token_key" -eibxcp geqqosgi""token_secret" yccfemmc wyf qoipbo"codethe twitter web service are accessed using url like thisbut once all of the security information has been addedthe url will look more like&oauth_version= &oauth_token= sgi&screen_name=drchuck &oauth_nonce= &oauth_timestamp= &oauth_signature=rlk bod&oauth_consumer_key= lu gng &oauth_signature_method=hmac-sha you can read the oauth specification if you want to know more about the meaning of the various parameters that are added to meet the security requirements of oauth |
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 twitter user and returns it to us in json format in string we simply print the first characters of the stringimport urllib requesturllib parseurllib error import twurl import ssl create app and get the four stringsput them in hidden py twitter_url 'ignore ssl certificate errors ctx ssl create_default_context(ctx check_hostname false ctx verify_mode ssl cert_none while trueprint(''acct input('enter twitter account:'if (len(acct )break url twurl augment(twitter_url{'screen_name'acct'count'' '}print('retrieving'urlconnection urllib request urlopen(urlcontext=ctxdata connection read(decode(print(data[: ]headers dict(connection getheaders()print headers print('remaining'headers[' -rate-limit-remaining']codewhen the program runs it produces the following outputenter twitter account:drchuck retrieving [{"created_at":"sat sep : : + ",id": ,"id_str":" ""text":"rt @fixpertsee how the dutch handle traffic intersectionshttp:\/\/ co\/tiivwtehj \ #brilliant""source":"web","truncated":false,"in_rep remaining enter twitter account:fixpert |
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 about the request in the http response headers one header in particularx-rate-limit-remaininginforms us how many more requests we can make before we will be shut off for short time period you can see that our remaining retrievals drop by one each time we make request to the api in the following examplewe retrieve user' twitter friendsparse the returned jsonand extract some of the information about the friends we also dump the json after parsing and "pretty-printit with an indent of four characters to allow us to pore through the data when we want to extract more fields import urllib requesturllib parseurllib error import twurl import json import ssl create app and get the four stringsput them in hidden py twitter_url 'ignore ssl certificate errors ctx ssl create_default_context(ctx check_hostname false ctx verify_mode ssl cert_none while trueprint(''acct input('enter twitter account:'if (len(acct )break url twurl augment(twitter_url{'screen_name'acct'count'' '}print('retrieving'urlconnection urllib request urlopen(urlcontext=ctxdata connection read(decode(js json loads(dataprint(json dumps(jsindent= )headers dict(connection getheaders()print('remaining'headers[' -rate-limit-remaining'] |
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 code the output of the program looks as follows (some of the data items are shortened to fit on the page)enter twitter account:drchuck retrieving remaining "next_cursor" "users""id" "followers_count" "status""text""@jazzychad just bought one __ ""created_at""fri sep : : + ""retweeted"false}"location""san franciscocalifornia""screen_name""leahculver""name""leah culver"}"id" "followers_count" "status""text""rt @wsjbig employers like google ""created_at""sat sep : : + "}"location""victoria canada""screen_name""_valeriei""name""valerie irvine"]"next_cursor_str"" |
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 the output is where we see the for loop reading the five most recent "friendsof the @drchuck twitter account and printing the most recent status for each friend there is great deal more data available in the returned json if you look in the output of the programyou can also see that the "find the friendsof particular account has different rate limitation than the number of timeline queries we are allowed to run per time period these secure api keys allow twitter to have solid confidence that they know who is using their api and data and at what level the rate-limiting approach allows us to do simplepersonal data retrievals but does not allow us to build product that pulls data from their api millions of times per day |
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 data structures like liststuplesand dictionaries as we build programswe design data structures and write code to manipulate those data structures there are many ways to write programs and by nowyou probably have written some programs that are "not so elegantand other programs that are "more eleganteven though your programs may be smallyou are starting to see how there is bit of art and aesthetic to writing code as programs get to be millions of lines longit becomes increasingly important to write code that is easy to understand if you are working on million-line programyou can never keep the entire program in your mind at the same time we need ways to break large programs into multiple smaller pieces so that we have less to look at when solving problemfix bugor add new feature in wayobject oriented programming is way to arrange your code so that you can zoom into lines of the code and understand it while ignoring the other , lines of code for the moment |
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 the key outcome of this is to have basic understanding of how objects are constructed and how they function and most importantly how we make use of the capabilities of objects that are provided to us by python and python libraries using objects as it turns outwe have been using objects all along in this book python provides us with many built-in objects here is some simple code where the first few lines should feel very simple and natural to you stuff list(stuff append('python'stuff append('chuck'stuff sort(print (stuff[ ]print (stuff __getitem__( )print (list __getitem__(stuff, )codeinstead of focusing on what these lines accomplishlet' look at what is really happening from the point of view of object-oriented programming don' worry if the following paragraphs don' make any sense the first time you read them because we have not yet defined all of these terms the first line constructs an object of type listthe second and third lines call the append(methodthe fourth line calls the sort(methodand the fifth line retrieves the item at position the sixth line calls the __getitem__(method in the stuff list with parameter of zero print (stuff __getitem__( )the seventh line is an even more verbose way of retrieving the th item in the list print (list __getitem__(stuff, )in this codewe call the __getitem__ method in the list class and pass the list and the item we want retrieved from the list as parameters |
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__''__delattr__''__delitem__''__dir__''__doc__''__eq__''__format__''__ge__''__getattribute__''__getitem__''__gt__''__hash__''__iadd__''__imul__''__init__''__iter__''__le__''__len__''__lt__''__mul__''__ne__''__new__''__reduce__''__reduce_ex__''__repr__''__reversed__''__rmul__''__setattr__''__setitem__''__sizeof__''__str__''__subclasshook__''append''clear''copy''count''extend''index''insert''pop''remove''reverse''sort'the rest of this will define all of the above terms so make sure to come back after you finish the and re-read the above paragraphs to check your understanding starting with programs program in its most basic form takes some inputdoes some processingand produces some output our elevator conversion program demonstrates very short but complete program showing all three of these steps usf input('enter the us floor number'wf int(usf print('non-us floor number is',wfcodeif we think bit more about this programthere is the "outside worldand the program the input and output aspects are where the program interacts with the outside world within the program we have code and data to accomplish the task the program is designed to solve one way to think about object-oriented programming is that it separates our program into multiple "zones each zone contains some code and data (like programand has well defined interactions with the outside world and the other zones within the program if we look back at the link extraction application where we used the beautifulsoup librarywe can see program that is constructed by connecting different objects together to accomplish task |
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_hostname false ctx verify_mode ssl cert_none url input('enter 'html urllib request urlopen(urlcontext=ctxread(soup beautifulsoup(html'html parser'retrieve all of the anchor tags tags soup(' 'for tag in tagsprint(tag get('href'none)codewe read the url into string and then pass that into urllib to retrieve the data from the web the urllib library uses the socket library to make the actual network connection to retrieve the data we take the string that urllib returns and hand it to beautifulsoup for parsing beautifulsoup makes use of the object html parser and returns an object we call the tags(method on the returned object that returns dictionary of tag objects we loop through the tags and call the get(method for each tag to print out the href attribute we can draw picture of this program and how the objects work together the key here is not to understand perfectly how this program works but to see how we build network of interacting objects and orchestrate the movement of information between the objects to create program it is also important to note that when you looked at that program several backyou could fully understand what was going on in the program without even realizing that the |
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 the object-oriented approach is that it can hide complexity for examplewhile we need to know how to use the urllib and beautifulsoup codewe do not need to know how those libraries work internally this allows us to focus on the part of the problem we need to solve and ignore the other parts of the program input string object urllib object socket object dictionary object string object output beautifulsoup object html parser object figure ignoring detail when using an object this ability to focus exclusively on the part of program that we care about and ignore the rest is also helpful to the developers of the objects that we use for examplethe programmers developing beautifulsoup do not need to know or care about how we retrieve our html pagewhat parts we want to reador what we plan to do with the data we extract from the web page our first python object at basic levelan object is simply some code plus data structures that are smaller than whole program defining function allows us to store bit of code and give it name and then later invoke that code using the name of the function |
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 call data items that are part of the object attributes we use the class keyword to define the data and code that will make up each of the objects the class keyword includes the name of the class and begins an indented block of code where we include the attributes (dataand methods (codeclass partyanimalx def party(selfself self print("so far",self xan partyanimal(an party(an party(an party(partyanimal party(ancodeeach method looks like functionstarting with the def keyword and consisting of an indented block of code this object has one attribute (xand one method (partythe methods have special first parameter that we name by convention self just as the def keyword does not cause function code to be executedthe class keyword does not create an object insteadthe class keyword defines template indicating what data and code will be contained in each object of type partyanimal the class is like cookie cutter and the objects created using the class are the cookies you don' put frosting on the cookie cutteryou put frosting on the cookiesand you can put different frosting on each cookie if we continue through this sample programwe see the first executable line of code cookie image copyright cc-by |
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 in way this is quite similar to the following line which we have been using all alongcounts dict(here we instruct python to construct an object using the dict template (already present in python)return the instance of dictionaryand assign it to the variable counts when the partyanimal class is used to construct an objectthe variable an is used to point to that object we use an to access the code and data for that particular instance of the partyanimal class each partyanimal object/instance contains within it variable and method/function named party we call the party method in this linean party(when the party method is calledthe first parameter (which we call by convention selfpoints to the particular instance of the partyanimal object that party is called from within the party methodwe see the lineself self this syntax using the dot operator is saying 'the within self each time party(is calledthe internal value is incremented by and the value is printed out the following line is another way to call the party method within the an objectpartyanimal party(an |
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 the object is constructedand the party method is called four timesboth incrementing and printing the value for within the an object classes as types as we have seenin python all variables have type we can use the built-in dir function to examine the capabilities of variable we can also use type and dir with the classes that we create class partyanimalx def party(selfself self print("so far",self xan partyanimal(print ("type"type(an)print ("dir "dir(an)print ("type"type(an )print ("type"type(an party)codewhen this program executesit produces the following outputtype dir ['__class__''__delattr__''__sizeof__''__str__''__subclasshook__''__weakref__''party'' 'type type you can see that using the class keywordwe have created new type from the dir outputyou can see both the integer attribute and the party method are available in the object |
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 more complexwe need to take some action within the object to set things up as the object is constructed and possibly clean things up as the object is discarded if we want our object to be aware of these moments of construction and destructionwe add specially named methods to our objectclass partyanimalx def __init__(self)print(' am constructed'def party(selfself self print('so far',self xdef __del__(self)print(' am destructed'self xan partyanimal(an party(an party(an print('an contains',ancodewhen this program executesit produces the following outputi am constructed so far so far am destructed an contains as python constructs our objectit calls our __init__ method to give us chance to set up some default or initial values for the object when python encounters the linean it actually "throws our object awayso it can reuse the an variable to store the value just at the moment when our an object is being "destroyedour destructor code (__del__is called we cannot stop our variable from being destroyedbut we can do any necessary cleanup right before our object no longer exists |
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 howeverthe real power in object-oriented programming happens when we construct multiple instances of our class when we construct multiple objects from our classwe might want to set up different initial values for each of the objects we can pass data to the constructors to give each object different initial valueclass partyanimalx name 'def __init__(selfnam)self name nam print(self name,'constructed'def party(selfself self print(self name,'party count',self xs partyanimal('sally' partyanimal('jim' party( party( party(codethe constructor has both self parameter that points to the object instance and additional parameters that are passed into the constructor as the object is constructeds partyanimal('sally'within the constructorthe second line copies the parameter (namthat is passed into the name attribute within the object instance self name nam the output of the program shows that each of the objects ( and jcontain their own independent copies of and nam |
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 for this examplewe move our partyanimal class into its own file thenwe can 'importthe partyanimal class in new file and extend itas followsfrom party import partyanimal class cricketfan(partyanimal)points def six(self)self points self points self party(print(self name,"points",self pointss partyanimal("sally" party( cricketfan("jim" party( six(print(dir( )codewhen we define the cricketfan classwe indicate that we are extending the partyanimal class this means that all of the variables (xand methods (partyfrom the partyanimal class are inherited by the cricketfan class for examplewithin the six method in the cricketfan classwe call the party method from the partyanimal class as the program executeswe create and as independent instances of partyanimal and cricketfan the object has additional capabilities beyond the object sally constructed sally party count jim constructed jim party count jim party count jim points ['__class__''__delattr__''__weakref__''name''party''points''six'' ' |
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 object-oriented programming that focuses mainly on terminology and the syntax of defining and using objects let' quickly review the code that we looked at in the beginning of the at this point you should fully understand what is going on stuff list(stuff append('python'stuff append('chuck'stuff sort(print (stuff[ ]print (stuff __getitem__( )print (list __getitem__(stuff, )codethe first line constructs list object when python creates the list objectit calls the constructor method (named __init__to set up the internal data attributes that will be used to store the list data we have not passed any parameters to the constructor when the constructor returnswe use the variable stuff to point to the returned instance of the list class the second and third lines call the append method with one parameter to add new item at the end of the list by updating the attributes within stuff then in the fourth linewe call the sort method with no parameters to sort the data within the stuff object we then print out the first item in the list using the square brackets which are shortcut to calling the __getitem__ method within the stuff this is equivalent to calling the __getitem__ method in the list class and passing the stuff object as the first parameter and the position we are looking for as the second parameter at the end of the programthe stuff object is discarded but not before calling the destructor (named __del__so that the object can clean up any loose ends as necessary those are the basics of object-oriented programming there are many additional details as to how to best use object-oriented approaches when developing large applications and libraries that are beyond the scope of this if you are curious about where the list class is definedtake look at (hopefully the url won' changeclass is written in language called "cif you take look at that source code and find it curious you might want to explore few computer science courses |
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 an optional specially named method (__init__that is called at the moment when class is being used to construct an object usually this is used to set up initial values for the object destructor an optional specially named method (__del__that is called at the moment just before an object is destroyed destructors are rarely used inheritance when we create new class (childby extending an existing class (parentthe child class has all the attributes and methods of the parent class plus additional attributes and methods defined by the child class method function that is contained within class and the objects that are constructed from the class some object-oriented patterns use 'messageinstead of 'methodto describe this concept object constructed instance of class an object contains all of the attributes and methods that were defined by the class some object-oriented documentation uses the term 'instanceinterchangeably with 'objectparent class the class which is being extended to create new child class the parent class contributes all of its methods and attributes to the new child class |
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 database is stored on permanent storageit can store far more data than dictionarywhich is limited to the size of the memory in the computer like dictionarydatabase software is designed to keep the inserting and accessing of data very fasteven for large amounts of data database software maintains its performance by building indexes as data is added to the database to allow the computer to jump quickly to particular entry there are many different database systems which are used for wide variety of purposes includingoraclemysqlmicrosoft sql serverpostgresqland sqlite we focus on sqlite in this book because it is very common database and is already built into python sqlite is designed to be embedded into other applications to provide database support within the application for examplethe firefox browser also uses the sqlite database internally as do many other products sqlite is well suited to some of the data manipulation problems that we see in informatics such as the twitter spidering application that we describe in this database concepts when you first look at database it looks like spreadsheet with multiple sheets the primary data structures in database aretablesrowsand columns in technical descriptions of relational databases the concepts of tablerowand column are more formally referred to as relationtupleand attributerespectively we will use the less formal terms in this |
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 available fromusing the browser you can easily create tablesinsert dataedit dataor run simple sql queries on the data in the database in sensethe database browser is similar to text editor when working with text files when you want to do one or very few operations on text fileyou can just open it in text editor and make the changes you want when you have many changes that you need to do to text fileoften you will write simple python program you will find the same pattern when working with databases you will do simple operations in the database manager and more complex operations will be most conveniently done in python creating database table databases require more defined structure than python lists or dictionaries when we create database table we must tell the database in advance the names of each of the columns in the table and the type of data which we are planning to store in each column when the database software knows the type of data in each columnit can choose the most efficient way to store and look up the data based on the type of data you can look at the various data types supported by sqlite at the following urldefining structure for your data up front may seem inconvenient at the beginningbut the payoff is fast access to your data even when the database contains large amount of data sqlite actually does allow some flexibility in the type of data stored in columnbut we will keep our data types strict in this so the concepts apply equally to other database systems such as mysql |
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 "connectionto the database stored in the file music sqlite in the current directory if the file does not existit will be created the reason this is called "connectionis that sometimes the database is stored on separate "database serverfrom the server on which we are running our application in our simple examples the database will just be local file in the same directory as the python code we are running cursor is like file handle that we can use to perform operations on the data stored in the database calling cursor(is very similar conceptually to calling open(when dealing with text files execute fetchone fetchall close users courses members your program figure database cursor once we have the cursorwe can begin to execute commands on the contents of the database using the execute(method database commands are expressed in special language that has been standardized across many different database vendors to allow us to learn single database language the database language is called structured query language or sql for short in our examplewe are executing two sql commands in our database as conventionwe will show the sql keywords in uppercase and the parts of the |
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 error note that the drop table command deletes the table and all of its contents from the database ( there is no "undo"cur execute('drop table if exists tracks 'the second command creates table named tracks with text column named title and an integer column named plays cur execute('create table tracks (title textplays integer)'now that we have created table named trackswe can put some data into that table using the sql insert operation againwe begin by making connection to the database and obtaining the cursor we can then execute sql commands using the cursor the sql insert command indicates which table we are using and then defines new row by listing the fields we want to include (titleplaysfollowed by the values we want placed in the new row we specify the values as question marks (??to indicate that the actual values are passed in as tuple 'my way' as the second parameter to the execute(call import sqlite conn sqlite connect('music sqlite'cur conn cursor(cur execute('insert into tracks (titleplaysvalues (??)'('thunderstruck' )cur execute('insert into tracks (titleplaysvalues (??)'('my way' )conn commit(print('tracks:'cur execute('select titleplays from tracks'for row in curprint(rowcur execute('delete from tracks where plays 'conn commit(cur close(code |
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 (titleplaysand indicate which table we want to retrieve the data from after we execute the select statementthe cursor is something we can loop through in for statement for efficiencythe cursor does not read all of the data from the database when we execute the select statement insteadthe data is read on demand as we loop through the rows in the for statement the output of the program is as followstracks('thunderstruck' ('my way' our for loop finds two rowsand each row is python tuple with the first value as the title and the second value as the number of plays noteyou may see strings starting with uin other books or on the internet this was an indication in python that the strings are unicodestrings that are capable of storing non-latin character sets in python all strings are unicode strings by default at the very end of the programwe execute an sql command to delete the rows we have just created so we can run the program over and over the delete command shows the use of where clause that allows us to express selection criterion so that we can ask the database to apply the command to only the rows that match the criterion in this example the criterion happens to apply to all the rows so we empty the table out so we can run the program repeatedly after the delete is performedwe also call commit(to force the data to be removed from the database structured query language summary so farwe have been using the structured query language in our python examples and have covered many of the basics of the sql commands in this sectionwe look at the sql language in particular and give an overview of sql syntax |
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 date data when we create tablewe indicate the names and types of the columnscreate table tracks (title textplays integerto insert row into tablewe use the sql insert commandinsert into tracks (titleplaysvalues ('my way' the insert statement specifies the table namethen list of the fields/columns that you would like to set in the new rowand then the keyword values and list of corresponding values for each of the fields the sql select command is used to retrieve rows and columns from database the select statement lets you specify which columns you would like to retrieve as well as where clause to select which rows you would like to see it also allows an optional order by clause to control the sorting of the returned rows select from tracks where title 'my wayusing indicates that you want the database to return all of the columns for each row that matches the where clause noteunlike in pythonin sql where clause we use single equal sign to indicate test for equality rather than double equal sign other logical operations allowed in where clause include =!=as well as and and or and parentheses to build your logical expressions you can request that the returned rows be sorted by one of the fields as followsselect title,plays from tracks order by title to remove rowyou need where clause on an sql delete statement the where clause determines which rows are to be deleteddelete from tracks where title 'my wayit is possible to update column or columns within one or more rows in table using the sql update statement as followsupdate tracks set plays where title 'my waythe update statement specifies table and then list of fields and values to change after the set keyword and then an optional where clause to select the rows that are to be updated single update statement will change all of the rows that match the where clause if where clause is not specifiedit performs the update on all of the rows in the table these four basic sql commands (insertselectupdateand deleteallow the four basic operations needed to create and maintain data |
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 of the problems of any kind of spidering program is that it needs to be able to be stopped and restarted many times and you do not want to lose the data that you have retrieved so far you don' want to always restart your data retrieval at the very beginning so we want to store data as we retrieve it so our program can start back up and pick up where it left off we will start by retrieving one person' twitter friends and their statuseslooping through the list of friendsand adding each of the friends to database to be retrieved in the future after we process one person' twitter friendswe check in our database and retrieve one of the friends of the friend we do this over and overpicking an "unvisitedpersonretrieving their friend listand adding friends we have not seen to our list for future visit we also track how many times we have seen particular friend in the database to get some sense of their "popularityby storing our list of known accounts and whether we have retrieved the account or notand how popular the account is in database on the disk of the computerwe can stop and restart our program as many times as we like this program is bit complex it is based on the code from the exercise earlier in the book that uses the twitter api here is the source code for our twitter spidering applicationfrom urllib request import urlopen import urllib error import twurl import json import sqlite import ssl twitter_url 'conn sqlite connect('spider sqlite'cur conn cursor(cur execute(''create table if not exists twitter (name textretrieved integerfriends integer)'''ignore ssl certificate errors ctx ssl create_default_context(ctx check_hostname false ctx verify_mode ssl cert_none |
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('retrieving'urlconnection urlopen(urlcontext=ctxdata connection read(decode(headers dict(connection getheaders()print('remaining'headers[' -rate-limit-remaining']js json loads(datadebugging print json dumps(jsindent= cur execute('update twitter set retrieved= where name ?'(acct)countnew countold for in js['users']friend ['screen_name'print(friendcur execute('select friends from twitter where name limit '(friend)trycount cur fetchone()[ cur execute('update twitter set friends where name ?'(count+ friend)countold countold exceptcur execute('''insert into twitter (nameretrievedfriendsvalues (? )'''(friend)countnew countnew print('new accounts='countnewrevisited='countoldconn commit(cur close(codeour database is stored in the file spider sqlite and it has one table named twitter each row in the twitter table has column for the account namewhether we have retrieved the friends of this accountand how many times this account has been "friended |
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 field in the row in the database if the user presses enterwe look in the database for the next twitter account that we have not yet retrievedretrieve the friends and statuses for that accountadd them to the database or update themand increase their friends count once we retrieve the list of friends and statuseswe loop through all of the user items in the returned json and retrieve the screen_name for each user then we use the select statement to see if we already have stored this particular screen_name in the database and retrieve the friend count (friendsif the record exists countnew countold for in js['users'friend ['screen_name'print(friendcur execute('select friends from twitter where name limit '(friendtrycount cur fetchone()[ cur execute('update twitter set friends where name ?'(count+ friendcountold countold exceptcur execute('''insert into twitter (nameretrievedfriendsvalues ? )'''friendcountnew countnew print('new accounts=',countnew,revisited=',countoldconn commit(once the cursor executes the select statementwe must retrieve the rows we could do this with for statementbut since we are only retrieving one row (limit )we can use the fetchone(method to fetch the first (and onlyrow that is the result of the select operation since fetchone(returns the row as tuple (even though there is only one field)we take the first value from the tuple using to get the current friend count into the variable count if this retrieval is successfulwe use the sql update statement with where clause to add to the friends column for the row that matches the friend' account notice that there are two placeholders ( question marksin the sqland the second parameter to the execute(is two-element tuple that holds the values to be substituted into the sql in place of the question marks if the code in the try block failsit is probably because no record matched the where name clause on the select statement so in the except blockwe use the sql insert statement to add the friend' screen_name to the table with an indication that we have not yet retrieved the screen_name and set the friend count to one |
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 the file spider sqlite and add table named twitter to the database then we retrieve some friends and add them all to the database since the database is empty at this pointwe might want to write simple database dumper to take look at what is in our spider sqlite fileimport sqlite conn sqlite connect('spider sqlite'cur conn cursor(cur execute('select from twitter'count for row in curprint(rowcount count print(count'rows 'cur close(codethis program simply opens the database and selects all of the columns of all of the rows in the table twitterthen loops through the rows and prints out each row if we run this program after the first execution of our twitter spider aboveits output will be as follows('opencontent' ('lhawthorn' ('steve_coppin' ('davidkocher' ('hrheingold' rows we see one row for each screen_namethat we have not retrieved the data for that screen_nameand everyone in the database has one friend now our database reflects the retrieval of the friends of our first twitter account (drchuckwe can run the program again and tell it to retrieve the friends of the next "unprocessedaccount by simply pressing enter instead of twitter account as follows |
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 'tryacct cur fetchone()[ exceptprint('no unretrieved twitter accounts found'continue we use the sql select statement to retrieve the name of the first (limit user who still has their "have we retrieved this uservalue set to zero we also use the fetchone()[ pattern within try/except block to either extract screen_name from the retrieved data or put out an error message and loop back up if we successfully retrieved an unprocessed screen_namewe retrieve their data as followsurl=twurl augment(twitter_url,{'screen_name'acct,'count'' '}print('retrieving'urlconnection urllib urlopen(urldata connection read(js json loads(datacur execute('update twitter set retrieved= where name ?',(acct)once we retrieve the data successfullywe use the update statement to set the retrieved column to to indicate that we have completed the retrieval of the friends of this account this keeps us from retrieving the same data over and over and keeps us progressing forward through the network of twitter friends if we run the friend program and press enter twice to retrieve the next unvisited friend' friendsthen run the dumping programit will give us the following output('opencontent' ('lhawthorn' ('steve_coppin' ('davidkocher' ('hrheingold' ('cnxorg' ('knoop' |
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 friends to retrieve each time we run the program and press enter it will pick the next unvisited account ( the next account will be steve_coppin)retrieve their friendsmark them as retrievedand for each of the friends of steve_coppin either add them to the end of the database or update their friend count if they are already in the database since the program' data is all stored on disk in databasethe spidering activity can be suspended and resumed as many times as you like with no loss of data basic data modeling the real power of relational database is when we create multiple tables and make links between those tables the act of deciding how to break up your application data into multiple tables and establishing the relationships between the tables is called data modeling the design document that shows the tables and their relationships is called data model data modeling is relatively sophisticated skill and we will only introduce the most basic concepts of relational data modeling in this section for more detail on data modeling you can start withlet' say for our twitter spider applicationinstead of just counting person' friendswe wanted to keep list of all of the incoming relationships so we could find list of everyone who is following particular account since everyone will potentially have many accounts that follow themwe cannot simply add single column to our twitter table so we create new table that keeps track of pairs of friends the following is simple way of making such tablecreate table pals (from_friend textto_friend texteach time we encounter person who drchuck is followingwe would insert row of the forminsert into pals (from_friend,to_friendvalues ('drchuck''lhawthorn'as we are processing the friends from the drchuck twitter feedwe will insert records with "drchuckas the first parameter so we will end up duplicating the string many times in the database |
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 termsa string takes up lot more space than an integer on the disk and in the memory of our computerand takes more processor time to compare and sort if we only have few hundred entriesthe storage and processor time hardly matters but if we have million people in our database and possibility of million friend linksit is important to be able to scan data as quickly as possible we will store our twitter accounts in table named people instead of the twitter table used in the previous example the people table has an additional column to store the numeric key associated with the row for this twitter user sqlite has feature that automatically adds the key value for any row we insert into table using special type of data column (integer primary keywe can create the people table with this additional id column as followscreate table people (id integer primary keyname text uniqueretrieved integernotice that we are no longer maintaining friend count in each row of the people table when we select integer primary key as the type of our id columnwe are indicating that we would like sqlite to manage this column and assign unique numeric key to each row we insert automatically we also add the keyword unique to indicate that we will not allow sqlite to insert two rows with the same value for name now instead of creating the table pals abovewe create table called follows with two integer columns from_id and to_id and constraint on the table that the combination of from_id and to_id must be unique in this table ( we cannot insert duplicate rowsin our database create table follows (from_id integerto_id integerunique(from_idto_idwhen we add unique clauses to our tableswe are communicating set of rules that we are asking the database to enforce when we attempt to insert records we are creating these rules as convenience in our programsas we will see in moment the rules both keep us from making mistakes and make it simpler to write some of our code in essencein creating this follows tablewe are modelling "relationshipwhere one person "followssomeone else and representing it with pair of numbers indicating that (athe people are connected and (bthe direction of the relationship programming with multiple tables we will now redo the twitter spider program using two tablesthe primary keysand the key references as described above here is the code for the new version of the program |
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 execute('''create table if not exists people (id integer primary keyname text uniqueretrieved integer)'''cur execute('''create table if not exists follows (from_id integerto_id integerunique(from_idto_id))'''ignore ssl certificate errors ctx ssl create_default_context(ctx check_hostname false ctx verify_mode ssl cert_none while trueacct input('enter twitter accountor quit'if (acct ='quit')break if (len(acct )cur execute('select idname from people where retrieved= limit 'try(idacctcur fetchone( |
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 url twurl augment(twitter_url{'screen_name'acct'count'' '}print('retrieving account'accttryconnection urllib request urlopen(urlcontext=ctxexcept exception as errprint('failed to retrieve'errbreak data connection read(decode(headers dict(connection getheaders()print('remaining'headers[' -rate-limit-remaining']tryjs json loads(dataexceptprint('unable to parse json'print(databreak debugging print(json dumps(jsindent= )if 'usersnot in jsprint('incorrect json received'print(json dumps(jsindent= )continue cur execute('update people set retrieved= where name ?'(acct)countnew countold for in js['users']friend ['screen_name' |
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 lastrowid countnew countnew cur execute('''insert or ignore into follows (from_idto_idvalues (??)'''(idfriend_id)print('new accounts='countnewrevisited='countoldprint('remaining'headers[' -rate-limit-remaining']conn commit(cur close(codethis program is starting to get bit complicatedbut it illustrates the patterns that we need to use when we are using integer keys to link tables the basic patterns are create tables with primary keys and constraints when we have logical key for person ( account nameand we need the id value for the persondepending on whether or not the person is already in the people table we either need to( look up the person in the people table and retrieve the id value for the person or ( add the person to the people table and get the id value for the newly added row insert the row that captures the "followsrelationship we will cover each of these in turn constraints in database tables as we design our table structureswe can tell the database system that we would like it to enforce few rules on us these rules help us from making mistakes and introducing incorrect data into our tables when we create our tablescur execute('''create table if not exists people (id integer primary keyname text uniqueretrieved integer)'''cur execute('''create table if not exists follows (from_id integerto_id integerunique(from_idto_id))''' |
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 the following codecur execute('''insert or ignore into people (nameretrievedvalues ? )'''friendwe add the or ignore clause to our insert statement to indicate that if this particular insert would cause violation of the "name must be uniquerulethe database system is allowed to ignore the insert we are using the database constraint as safety net to make sure we don' inadvertently do something incorrect similarlythe following code ensures that we don' add the exact same follows relationship twice cur execute('''insert or ignore into follows (from_idto_idvalues (??)'''(idfriend_idagainwe simply tell the database to ignore our attempted insert if it would violate the uniqueness constraint that we specified for the follows rows retrieve and/or insert record when we prompt the user for twitter accountif the account existswe must look up its id value if the account does not yet exist in the people tablewe must insert the record and get the id value from the inserted row this is very common pattern and is done twice in the program above this code shows how we look up the id for friend' account when we have extracted screen_name from user node in the retrieved twitter json since over time it will be increasingly likely that the account will already be in the databasewe first check to see if the people record exists using select statement if all goes well inside the try sectionwe retrieve the record using fetchone(and then retrieve the first (and onlyelement of the returned tuple and store it in friend_id if the select failsthe fetchone()[ code will fail and control will transfer into the except section friend ['screen_name'cur execute('select id from people where name limit '(friendtry in generalwhen sentence starts with "if all goes wellyou will find that the code needs to use try/except |
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 that the row was not foundso we must insert the row we use insert or ignore just to avoid errors and then call commit(to force the database to really be updated after the write is donewe can check the cur rowcount to see how many rows were affected since we are attempting to insert single rowif the number of affected rows is something other than it is an error if the insert is successfulwe can look at cur lastrowid to find out what value the database assigned to the id column in our newly created row storing the friend relationship once we know the key value for both the twitter user and the friend in the jsonit is simple matter to insert the two numbers into the follows table with the following codecur execute('insert or ignore into follows (from_idto_idvalues (??)'(idfriend_idnotice that we let the database take care of keeping us from "double-insertinga relationship by creating the table with uniqueness constraint and then adding or ignore to our insert statement here is sample execution of this programenter twitter accountor quitno unretrieved twitter accounts found enter twitter accountor quitdrchuck retrieving new accounts revisited enter twitter accountor quitretrieving new accounts revisited enter twitter accountor quitretrieving new accounts revisited enter twitter accountor quitquit |
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 follows( ( ( ( ( rows you can see the idnameand visited fields in the people table and you see the numbers of both ends of the relationship in the follows table in the people tablewe can see that the first three people have been visited and their data has been retrieved the data in the follows table indicates that drchuck (user is friend to all of the people shown in the first five rows this makes sense because the first data we retrieved and stored was the twitter friends of drchuck if you were to print more rows from the follows tableyou would see the friends of users and as well three kinds of keys now that we have started building data model putting our data into multiple linked tables and linking the rows in those tables using keyswe need to look at some terminology around keys there are generally three kinds of keys used in database model logical key is key that the "real worldmight use to look up row in our example data modelthe name field is logical key it is the screen name for the user and we indeed look up user' row several times in the program using the name field you will often find that it makes sense to add unique constraint to logical key since the logical key is how we look up row from the outside worldit makes little sense to allow multiple rows with the same value in the table primary key is usually number that is assigned automatically by the database it generally has no meaning outside the program and is only used to link rows from different tables together when we want to look up row in tableusually searching for the row using the primary key is the fastest way to find the row since primary keys are integer numbersthey take up very little storage and can be compared or sorted very quickly in our data modelthe id field is an example of primary key |
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 foreign key using join to retrieve data now that we have followed the rules of database normalization and have data separated into two tableslinked together using primary and foreign keyswe need to be able to build select that reassembles the data across the tables sql uses the join clause to reconnect these tables in the join clause you specify the fields that are used to reconnect the rows between the tables the following is an example of select with join clauseselect from follows join people on follows from_id people id where people id the join clause indicates that the fields we are selecting cross both the follows and people tables the on clause indicates how the two tables are to be joinedtake the rows from follows and append the row from people where the field from_id in follows is the same the id value in the people table people follows id name retrieved drchuck opencontent lhawthorn steve_coppin name id drchuck drchuck drchuck from_id to_id from_id to_id name opencontent lhawthorn steve_coppin figure connecting tables using join |
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 the following code demonstrates the data that we will have in the database after the multi-table twitter spider program (abovehas been run several times import sqlite conn sqlite connect('friends sqlite'cur conn cursor(cur execute('select from people'count print('people:'for row in curif count print(rowcount count print(count'rows 'cur execute('select from follows'count print('follows:'for row in curif count print(rowcount count print(count'rows 'cur execute('''select from follows join people on follows to_id people id where follows from_id '''count print('connections for id= :'for row in curif count print(rowcount count print(count'rows 'cur close(codein this programwe first dump out the people and follows and then dump out subset of the data in the tables joined together here is the output of the programpython twjoin py people |
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 select with the join clause in the last selectwe are looking for accounts that are friends of "opencontent( people id= in each of the "metarowsin the last selectthe first two columns are from the follows table followed by columns three through five from the people table you can also see that the second column (follows to_idmatches the third column (people idin each of the joined-up "metarows summary this has covered lot of ground to give you an overview of the basics of using database in python it is more complicated to write the code to use database to store data than python dictionaries or flat files so there is little reason to use database unless your application truly needs the capabilities of database the situations where database can be quite useful are( when your application needs to make many small random updates within large data set( when your data is so large it cannot fit in dictionary and you need to look up information repeatedlyor ( when you have long-running process that you want to be able to stop and restart and retain the data from one run to the next you can build simple database with single table to suit many application needsbut most problems will require several tables and links/relationships between rows in different tables when you start making links between tablesit is important to do some thoughtful design and follow the rules of database normalization to make the best use of the database' capabilities since the primary motivation for using database is that you have large amount of data to deal withit is important to model your data efficiently so your programs run as fast as possible |
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 to keep two programs from changing the same data at the same time for exampleif you open database in the browser and make change to the database and have not yet pressed the "savebutton in the browserthe browser "locksthe database file and keeps any other program from accessing the file in particularyour python program will not be able to access the file if it is locked so solution is to make sure to either close the database browser or use the file menu to close the database in the browser before you attempt to access the database from python to avoid the problem of your python code failing because the database is locked glossary attribute one of the values within tuple more commonly called "columnor "fieldconstraint when we tell the database to enforce rule on field or row in table common constraint is to insist that there can be no duplicate values in particular field ( all the values must be uniquecursor cursor allows you to execute sql commands in database and retrieve data from the database cursor is similar to socket or file handle for network connections and filesrespectively database browser piece of software that allows you to directly connect to database and manipulate the database directly without writing program foreign key numeric key that points to the primary key of row in another table foreign keys establish relationships between rows stored in different tables index additional data that the database software maintains as rows and inserts into table to make lookups very fast logical key key that the "outside worlduses to look up particular row for example in table of user accountsa person' email address might be good candidate as the logical key for the user' data normalization designing data model so that no data is replicated we store each item of data at one place in the database and reference it elsewhere using foreign key primary key numeric key assigned to each row that is used to refer to one row in table from another table often the database is configured to automatically assign primary keys as rows are inserted relation an area within database that contains tuples and attributes more typically called "tabletuple single entry in database table that is set of attributes more typically called "row |
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 help get you started in solving real-world problem each of the applications is zip file that you can download and extract onto your computer and execute building openstreetmap from geocoded data in this projectwe are using the openstreetmap geocoding api to clean up some user-entered geographic locations of university names and then placing the data on an actual openstreetmap to get starteddownload the application fromwww py com/code /opengeo zip the first problem to solve is that these geocoding apis are rate-limited to certain number of requests per day if you have lot of datayou might need to stop and restart the lookup process several times so we break the problem into two phases in the first phase we take our input "surveydata in the file where data and read it one line at timeand retrieve the geocoded information from google and store it in database geodata sqlite before we use the geocoding api for each user-entered locationwe simply check to see if we already have the data for that particular line of input the database is functioning as local "cacheof our geocoding data to make sure we never ask google for the same data twice you can restart the process at any time by removing the file geodata sqlite run the geoload py program this program will read the input lines in where data and for each line check to see if it is already in the database if we don' have the |
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 poland found in database american university in cairo found in database arizona state university found in database athens information technology retrieving opengeo? =bits+pilani retrieved characters {"type":"featurecoll retrieving opengeo? =babcock+university retrieved characters {"type":"featurecoll retrieving opengeo? =banaras+hindu+university retrieved characters {"type":"featurecoll the first five locations are already in the database and so they are skipped the program scans to the point where it finds new locations and starts retrieving them |
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 to get your database to have all of the geocoded data for your input once you have some data loaded into geodata sqliteyou can visualize the data using the geodump py program this program reads the database and writes the file where js with the locationlatitudeand longitude in the form of executable javascript code run of the geodump py program is as followsagh university of science and technologyczarnowiejskaczarna wieskrowodrzakrakowlesser poland voivodeship - poland academy of fine artskrakowskie przedmiescienorthern srodmiesciesrodmiesciewarsawmasovian voivodeship - poland lines were written to where js open the where html file in web browser to view the data the file where html consists of html and javascript to visualize google map it reads the most recent data in where js to get the data to be visualized here is the format of the where js filemydata [ , 'agh university of science and technologyczarnowiejskaczarna wieskrowodrzakrakowlesser poland voivodeship - poland '][ , 'academy of fine artskrakowskie przedmiescieesrodmiescie polnocnesrodmiesciewarsawmasovian voivodeship - poland']]this is javascript variable that contains list of lists the syntax for javascript list constants is very similar to pythonso the syntax should be familiar to you simply open where html in browser to see the locations you can hover over each map pin to find the location that the geocoding api returned for the user-entered input if you cannot see any data when you open the where html fileyou might want to check the javascript or developer console for your browser visualizing networks and interconnections in this applicationwe will perform some of the functions of search engine we will first spider small subset of the web and run simplified version of the |
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 zip figure page ranking the first program (spider pyprogram crawls web site and pulls series of pages into the database (spider sqlite)recording the links between pages you can restart the process at any time by removing the spider sqlite file and rerunning spider py enter web url or enter['how many pages: how many pagesin this sample runwe told it to crawl website and retrieve two pages if you restart the program and tell it to crawl more pagesit will not re-crawl any pages already in the database upon restart it goes to random non-crawled page and starts there so each successive run of spider py is additive enter web url or enter['how many pages: |
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 '( none '( none '( none ' rows this shows the number of incoming linksthe old page rankthe new page rankthe id of the pageand the url of the page the spdump py program only shows pages that have at least one incoming link to them once you have few pages in the databaseyou can run page rank on the pages using the sprank py program you simply tell it how many page rank iterations to run how many iterations: [( )( )( )( )( )you can dump the database again to see that page rank has been updated( '( '( '( ' rows you can run sprank py as many times as you like and it will simply refine the page rank each time you run it you can even run sprank py few times and then go spider few more pages with spider py and then run sprank py to reconverge the page rank values search engine usually runs both the crawling and ranking programs all the time if you want to restart the page rank calculations without respidering the web pagesyou can use spreset py and then restart sprank py how many iterations: |
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 should run sprank py long enough that the page rank values converge if you want to visualize the current top pages in terms of page rankrun spjson py to read the database and write the data for the most highly linked pages in json format to be viewed in web browser creating json output on spider json how many nodes open force html in browser to view the visualization you can view this data by opening the file force html in your web browser this shows an automatic layout of the nodes and links you can click and drag any node and you can also double-click on node to find the url that is represented by the node if you rerun the other utilitiesrerun spjson py and press refresh in the browser to get the new data from spider json visualizing mail data up to this point in the bookyou have become quite familiar with our mboxshort txt and mbox txt data files now it is time to take our analysis of email data to the next level in the real worldsometimes you have to pull down mail data from servers that might take quite some time and the data might be inconsistenterror-filledand need lot of cleanup or adjustment in this sectionwe work with an application that is the most complex so far and pull down nearly gigabyte of data and visualize it you can download this application from |
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 api they have no rate limitsbut ask that you don' overload their service and take only the data you need you can read gmane' terms and conditions at this pageit is very important that you make use of the gmane org data responsibly by adding delays to your access of their services and spreading long-running jobs over longer period of time do not abuse this free service and ruin it for the rest of us when the sakai email data was spidered using this softwareit produced nearly gigabyte of data and took number of runs on several days the file readme txt in the above zip may have instructions as to how you can download pre-spidered copy of the content sqlite file for majority of the sakai email corpus so you don' have to spider for five days just to run the programs if you download the prespidered contentyou should still run the spidering process to catch up with more recent messages the first step is to spider the gmane repository the base url is hard-coded in the gmane py and is hard-coded to the sakai developer list you can spider another repository by changing that base url make sure to delete the content sqlite file if you switch the base url the gmane py file operates as responsible caching spider in that it runs slowly and retrieves one mail message per second so as to avoid getting throttled by gmane it stores all of its data in database and can be interrupted and restarted as often |
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 [building sakaimelete oracle shedid@elraed-it com [building sakaisamuelgutierrezjimenez@gmail com redoes not start with from the program scans content sqlite from one up to the first message number not already spidered and starts spidering at that message it continues spidering until it has spidered the desired number of messages or it reaches page that does not appear to be properly formatted message sometimes gmane org is missing message perhaps administrators can delete messages or perhaps they get lost if your spider stopsand it seems it has hit missing messagego into the sqlite manager and add row with the missing id leaving all the other fields blank and restart gmane py this will unstick the spidering process and allow it to continue these empty messages will be ignored in the next phase of the process one nice thing is that once you have spidered all of the messages and have them in content sqliteyou can run gmane py again to get new messages as they are sent to the list the content sqlite data is pretty rawwith an inefficient data modeland not compressed this is intentional as it allows you to look at content sqlite in the sqlite manager to debug problems with the spidering process it would be bad idea to run any queries against this databaseas they would be quite slow the second process is to run the program gmodel py this program reads the raw data from content sqlite and produces cleaned-up and well-modeled version of the data in the file index sqlite this file will be much smaller (often smallerthan content sqlite because it also compresses the header and body text each time gmodel py runs it deletes and rebuilds index sqliteallowing you to adjust its parameters and edit the mapping tables in content sqlite to tweak the data cleaning process this is sample run of gmodel py it prints line out each time mail messages are processed so you can see some progress happeningas this program may run for while processing nearly gigabyte of mail data loaded allsenders and mapping dns mapping |
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 and caret cam ac uk becomes cam ac uk email addresses are also forced to lower caseand some of the @gmane org address like the following arwhyte- axycvo tyhxe+lvdladg@public gmane org are converted to the real address whenever there is matching real email address elsewhere in the message corpus in the mapping sqlite database there are two tables that allow you to map both domain names and individual email addresses that change over the lifetime of the email list for examplesteve githens used the following email addresses as he changed jobs over the life of the sakai developer lists-githens@northwestern edu sgithens@cam ac uk swgithen@mtu edu we can add two entries to the mapping table in mapping sqlite so gmodel py will map all three to one addresss-githens@northwestern edu -swgithen@mtu edu sgithens@cam ac uk -swgithen@mtu edu you can also make similar entries in the dnsmapping table if there are multiple dns names you want mapped to single dns the following mapping was added to the sakai dataiupui edu -indiana edu so all the accounts from the various indiana university campuses are tracked together you can rerun the gmodel py over and over as you look at the dataand add mappings to make the data cleaner and cleaner when you are doneyou will have nicely indexed version of the email in index sqlite this is the file to use to do data analysis with this filedata analysis will be really quick the firstsimplest data analysis is to determine "who sent the most mail?and "which organization sent the most mail"this is done using gbasic py |
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 compared to gmane py or even gmodel py they are all working on the same databut gbasic py is using the compressed and normalized data in index sqlite if you have lot of data to managea multistep process like the one in this application may take little longer to developbut will save you lot of time when you really start to explore and visualize your data you can produce simple visualization of the word frequency in the subject lines in the file gword pyrange of counts output written to gword js this produces the file gword js which you can visualize using gword htm to produce word cloud similar to the one at the beginning of this section second visualization is produced by gline py it computes email participation by organizations over time loaded messages subjects senders top oranizations ['gmail com''umich edu''uct ac za''indiana edu''unicon net''tfd co uk''berkeley edu''longsight com''stanford edu''ox ac uk'output written to gline js its output is written to gline js which is visualized using gline htm this is relatively complex and sophisticated application and has features to do some real data retrievalcleaningand visualization |
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 see contribution details ata contributor list for python for informatics bruce shields for copy editing early draftssarah heggesteven cherrysarah kathleen barbarowandrea parkerradaphat chongthammakunmegan hixonkirby urnersarah kathleen barbrowkatie kujalanoah botimeremily alindermark thompson-kularjames perryeric hofereytan adarpeter robinsondeborah nelsonjonathan anthonyeden rassettejeannette schroederjustin feezellchuanqi ligerald gordiniergavin thomas strasselryan clementalissa talleycaitlin holmanyong-mi kimkaren stovercherie edmondsmaria seiferleromer kristi aranas (rk)grant boyerhedemarrie dussana preface for "think pythona the strange history of "think python(allen downeyin january was preparing to teach an introductory programming class in java had taught it three times and was getting frustrated the failure rate in |
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 effectthey would start out easyproceed graduallyand then somewhere around the bottom would fall out the students would get too much new materialtoo fastand would spend the rest of the semester picking up the pieces two weeks before the first day of classesi decided to write my own book my goals werekeep it short it is better for students to read pages than not read pages be careful with vocabulary tried to minimize the jargon and define each term at first use build gradually to avoid trap doorsi took the most difficult topics and split them into series of small steps focus on programmingnot the programming language included the minimum useful subset of java and left out the rest needed titleso on whim chose how to think like computer scientist my first version was roughbut it worked students did the readingand they understood enough that could spend class time on the hard topicsthe interesting topics and (most importantletting the students practice released the book under the gnu free documentation licensewhich allows users to copymodifyand distribute the book what happened next is the cool part jeff elknera high school teacher in virginiaadopted my book and translated it into python he sent me copy of his translationand had the unusual experience of learning python by reading my own book jeff and revised the bookincorporated case study by chris meyersand in we released how to think like computer scientistlearning with pythonalso under the gnu free documentation license as green tea pressi published the book and started selling hard copies through amazon com and college book stores other books from green tea press are available at greenteapress com in started teaching at olin college and got to teach python for the first time the contrast with java was striking students struggled lesslearned moreworked on more interesting projectsand generally had lot more fun over the last five years have continued to develop the bookcorrecting errorsimproving some of the examples and adding materialespecially exercises in started work on major revision--at the same timei was contacted by an editor at cambridge university press who was interested in publishing the next edition good timingi hope you enjoy working with this bookand that it helps you learn to program and thinkat least little bitlike computer scientist |
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 scientist and thank the free software foundation for developing the gnu free documentation licensewhich helped make my collaboration with jeff and chris possible also thank the editors at lulu who worked on how to think like computer scientist thank all the students who worked with earlier versions of this book and all the contributors (listed in an appendixwho sent in corrections and suggestions and thank my wifelisafor her work on this bookand green tea pressand everything elsetoo allen downey needham ma allen downey is an associate professor of computer science at the franklin olin college of engineering contributor list for "think python(allen downeymore than sharp-eyed and thoughtful readers have sent in suggestions and corrections over the past few years their contributionsand enthusiasm for this projecthave been huge help for the detail on the nature of each of the contributions from these individualssee the "think pythontext lloyd hugh allenyvon bouliannefred bremmerjonah cohenmichael conlonbenoit girardcourtney gleason and katherine smithlee harrjames kaylindavid kershaweddie lamman-yong leedavid mayochris mcaloonmatthew moeltersimon dicon montfordjohn ouztskevin parksdavid poolmichael schmittrobin shawpaul sleighcraig snydalian thomaskeith verheydenpeter winstanleychris wrobelmoshe zadkachristoph zwerschkejames mayerhayden mcafeeangel arnaltauhidul hoque and lex berezhnydr michele alzettaandy mitchellkalin harveychristopher smithdavid hutchinsgregor lingljulie petersflorin oprinad webrekenivo wevercurtis yankoben loganjason armstronglouis cordierbrian cainrob blackjean-philippe rey at ecole centrale parisjason mader at george washington university made number jan gundtofte-bruunabel david and alexis dinnocharles thayerroger sperbergsam bullandrew cheungc corey capelalessandrawim champagnedouglas wrightjared spindor |
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 hailperinchotipat pornavalaistanislaw antoleric pashmanmiguel azevedojianhua liunick kingmartin zutheradam zimmermanratnakar tiwarianurag goelkelli kratzermark griffithsroydan ongiepatryk wolowiecmark chonofskyrussell colemanwei huangkaren barbernam nguyenstephane morinfernando tardioand paul stoop |
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 organizations who search for and find freely licensed booksand then publish and sell virtually unchanged copies of the books on print on demand service such as lulu or kdp kdp has (thankfullyadded policy that gives the wishes of the actual copyright holder preference over non-copyright holder attempting to publish freely licensed work unfortunately there are many print-on-demand services and very few have as wellconsidered policy as kdp regretfullyi added the nc element to the license this book to give me recourse in case someone tries to clone this book and sell it commercially unfortunatelyadding nc limits uses of this material that would like to permit so have added this section of the document to describe specific situations where am giving my permission in advance to use the material in this book in situations that some might consider commercial if you are printing limited number of copies of all or part of this book for use in course ( like coursepack)then you are granted cc-by license to these materials for that purpose if you are teacher at university and you translate this book into language other than english and teach using the translated bookthen you can contact me and will grant you cc-by-sa license to these materials with respect to the publication of your translation in particularyou will be permitted to sell the resulting translated book commercially if you are intending to translate the bookyou may want to contact me so we can make sure that you have all of the related course materials so you can translate them as well of courseyou are welcome to contact me and ask for permission if these clauses are not sufficient in all casespermission to reuse and remix this material will be |
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 bracket squiggly bracket operator branch break statement bug by-saiv cache case-sensitivityvariable names catch cc-by-saiv celsius central processing unit chained conditional character child class choice function class float int str class keyword close method colon comment comparable comparison string tuple comparison operator compile composition compound statement concatenation list condition conditional chained nested conditional executions conditional statement connect function consistency check constraint construct constructor continue statement contributors conversion type copy slice to avoid aliasing count method |
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 indexerror ioerror by bisection keyerror decorate-sort-undecorate pattern typeerror decrement valueerror def keyword experimental debugging definition expression function boolean del statement extend method deletionelement of list extensible markup language delimiter fahrenheit destructor false special value deterministic file development plan open random walk programming reading dict function writing dictionary file handle looping with filter pattern traversal findall dir flag divisibility float function division float type floating-point floating-point dot notation floating-point division dsu pattern flow control element flow of execution element deletion for loop elementtree for statement find foreign key findall format operator fromstring format sequence get format string elif keyword free documentation licensegnu ellipses else keyword frequency email address letter empty list fruitful function |
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- - - (ebookpublisherwilliam pollock production managerrachel monaghan production editorpaula williamson developmental editorfrances saux technical reviewersarah kuchinsky cover and interior designoctopod studios cover illustratorjosh ellingson copyeditorbart reed compositormaureen foryshappenstance type- -rama proofreaderscout festa for information on book distributors or translationsplease contact no starch pressinc directlyno starch pressinc th streetsan franciscoca phone- info@nostarch com www nostarch com library of congress control number no starch press and the no starch press logo are registered trademarks of no starch pressinc other product and company names mentioned herein may be the trademarks of their respective owners rather than use trademark symbol with every occurrence of trademarked namewe are using the names only in an editorial fashion and to the benefit of the trademark ownerwith no intention of infringement of the trademark the information in this book is distributed on an "as isbasiswithout warranty while every precaution has been taken in the preparation of this workneither the author nor no starch pressinc shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it |
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 computer games with python his books are freely available under creative commons license at his website about the technical reviewer sarah kuchinskymsis corporate trainer and consultant she uses python for variety of applicationsincluding health systems modelinggame developmentand task automation sarah is co-founder of the north bay python conferencetutorials chair for pycon usand lead organizer for pyladies silicon valley she holds degrees in management science engineering and mathematics |
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 bitmap image work with multiline strings project blackjacka classic card game played against an ai dealer learn about unicode characters and code points project bouncing dvd logosimulates the colorful bouncing dvd logo of decades past work with coordinates and colorful text project caesar ciphera simple encryption scheme used thousands of years ago convert between letters and numbers to perform math on text project caesar hackera program to decrypt caesar cipher messages without the encryption key implement brute-force cryptanalysis algorithm project calendar makercreate calendar pages for given year and month use python' datetime module and the timedelta data type project carrot in boxa silly bluffing game between two players create ascii art project cho-hana gambling dice game from feudal japan practice using random numbers and dictionary data structures |
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 dictionary data structures and screen coordinates project countdowna countdown timer with seven-segment display practice importing modules you create project deep cavea tunnel animation that descends endlessly into the earth use string replication and simple math project diamondsan algorithm for drawing diamonds of various sizes practice your pattern recognition skills to create drawing algorithms project dice matha visual dice-rolling math game use dictionary data structures for screen coordinates project dice rollera tool for reading dungeons dragons dice notation to generate random numbers parse text to identify key strings project digital clocka clock with calculator-like display generate numbers that match information from the datetime module project digital streama scrolling screensaver that resembles the matrix experiment with different animation speeds project dna visualizationan endless ascii-art double helix that demonstrates the structure of dna work with string templates and randomly generated text project ducklingsmix and match strings to create variety of ascii-art ducks use object-oriented programming to create data model for duck drawings viii contents in detail |
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 fibonaccigenerate numbers in the famous fibonacci sequence implement rudimentary mathematics algorithm project fish tanka colorfulanimated ascii-art fish tank use screen coordinatestext colorsand data structures project flooderattempt to fill the entire puzzle board with one color implement the flood fill algorithm project forest fire simsimulate the spread of wildfires through forest create simulation with adjustable parameters project four in rowa board game where two players try to connect four tiles in row create data structure that mimics gravity project guess the numberthe classic number guessing game program basic concepts for beginners project gulliblea humorous program to keep gullible people busy for hours use input validation and loops project hacking minigamededuce password based on clues add cosmetic features to make basic game more interesting project hangman and guillotinethe classic word guessing game use string manipulation and ascii art project hex gridprogrammatically generate tiled ascii art use loops to make repeating text patterns contents in detail ix |
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 automata whose ants move according to simple rules explore how simple rules create complex graphical patterns project leetspeaktranslate english messages into ] use text parsing and string manipulation project lucky starsa push-your-luck dice game practice ascii art and probability project magic fortune balla program to answer your yes/no questions about the future add cosmetic features to make basic text appear more interesting project mancalathe ancient two-player board game from mesopotamia use ascii art and string templates to draw board game project maze runner dtry to escape maze read maze data from text files project maze runner dtry to escape maze in modify multiline strings to display view project million dice roll statistics simulatorexplore the probability results of rolling set of dice one million times learn how computers crunch large quantities of numbers project mondrian art generatorcreate geometric drawings in the style of piet mondrian implement an art-generating algorithm project monty hall problema simulation of the monty hall game show problem examine probability with ascii-art goats contents in detail |
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 systems countersexamine binary and hexadecimal numbers use python' number conversion functions project periodic table of the elementsan interactive database of chemical elements parse csv files to load data into program project pig latintranslates english messages into igpay atinlay use text parsing and string manipulation project powerball lotterysimulate losing at the lottery thousands of times explore probability using random numbers project prime numberscalculate prime numbers learn math concepts and use python' math module project progress bara sample progress bar animation to use in other programs use the backspace-printing technique to create animations project rainbowa simple rainbow animation create animation for beginners project rock paper scissorsthe classic hand game for two players implement basic game rules as program project rock paper scissors (always-win version) version of the game where the player cannot lose create the illusion of randomness in program contents in detail xi |
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 modulea display like those used in calculators and microwave ovens create modules for use in other programs project shining carpetprogrammatically generate the carpet from the shining use loops to make repeating text patterns project simple substitution cipheran encryption scheme more advanced than the caesar cipher perform intermediate math on text project sine messagedisplay scrolling wave message use trigonometry function for animation project sliding tile puzzlethe classic four-by-four tile puzzle employ data structure to reflect the state of game board project snail racefast-paced snail racing action calculate spacing for ascii art snails project soroban japanese abacusa computer simulation of pre-computer calculating tool use string templates to create an ascii-art counting tool project sound mimicmemorize an increasingly long pattern of sounds play sound files from python program project spongecasetranslates english messages into spongecase change the casing of letters in strings xii contents in detail |
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-toethe classic two-player board game of xs and os create data structure and helper functions project tower of hanoithe classic diskstacking puzzle use stack data structures to simulate puzzle state project trick questionsa quiz of simple questions with misleading answers parse the user' text to recognize keywords project twenty forty-eighta casual tile matching game simulate gravity to make tiles "fallin arbitrary directions project vigenere cipheran encryption scheme so advanced it remained unbreakable for hundreds of years until computers were invented perform more advanced math on text project water bucket puzzleobtain exactly four liters of water by filling and emptying three buckets use string templates to generate ascii art appendix atag index appendix bcharacter map contents in detail xiii |
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 programsmaybe you found it hard to fly on your own you found yourself staring at blank editor window and unsure of how to get started writing python programs of your own the problem is that following tutorial is great for learning conceptsbut that isn' necessarily the same thing as learning to create original programs from scratch the common advice given at this stage is to examine the source code of open source software or to work on your own projectsbut open source projects aren' always well documented or especially accessible to newcomers and while it' motivating to work on your own projectyou're left completely without guidance or structure |
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 start to get ideas for your own programs andmore importantlyknow how to go about creating them how to design small programs programming has proven to be powerful skillcreating billion-dollar tech companies and amazing technological advances it' easy to want to aim high with your own software creationsbut biting off more than you can chew can leave you with half-finished programs and frustration howeveryou don' need to be computer genius to code fun and creative programs the python programs in this book follow several design principles to aid new programmers in understanding their source codesmall most of these programs are limited to lines of code and are often significantly shorter this size limit makes them easier to comprehend the choice of is arbitrarybut is also and powers of are lucky programmer numbers text based text is simpler than graphics since the source code and program output are both textit' easy to trace the cause and effect between print('thanks for playing!'in the code and thanks for playingappearing on the screen no installation needed each program is self-contained in single python source file with the py file extensionlike tictactoe py you don' need to run an installer programand you can easily post these programs online to share with others numerous there are programs in this book between board gamescard gamesdigital artworksimulationsmathematical puzzlesmazesand humor programsyou're bound to find many things you'll love simple the programs have been written to be easy to understand by beginners whenever had to choose between writing code using sophisticatedhigh-performance algorithms or writing plainstraightforward codei've chosen the latter every time the text-based programs may seem old schoolbut this style of programming cuts out the distractions and potholes that downloading graphicsinstalling additional librariesand managing project folders bring insteadyou can just focus on the code who is this book forthis book is written for two groups of people the people in the first group are those who have already learned the basics of python and programming xvi introduction |
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 into variety of real programs the people in the second group are those who are new to programming but are excited and bit adventurous they want to dive right in and get started making gamessimulationsand number-crunching programs right away they're fine with copying the code and learning along the way or perhaps they already know how to program in another language but are new to python while it' no substitute for complete introductory python coursethis book contains brief introduction to python basics and how to use the debugger to examine the inner workings of program as it runs experienced programmers might have fun with the programs in this book as wellbut keep in mind that this book was written for beginners about this book while the bulk of this book is dedicated to the featured programsthere are also extra resources with general programming and python information here' what' contained in this bookprojects the projects are too numerous to list herebut each one is self-contained mini-that includes the project' namea descriptiona sample run of the program' outputand the source code of the program there are also suggestions for experimental edits you can make to the code to customize the program appendix atag index lists all of the projects categorized by their project tags appendix bcharacter map list of character codes for symbols such as heartslinesarrowsand blocks that your programs can print how to learn from the programs in this book this book doesn' teach python or programming concepts like traditional tutorial it has learn-by-doing approachwhere you're encouraged to manually copy the programsplay with themand inspect their inner workings by running them under debugger the point of this book isn' to give detailed explanation of programming language syntaxbut to show solid examples of programs that perform an actual activitywhether it' card gamean animationor exploration of mathematical puzzle as suchi recommend the following steps download the program and run it to see what the program does for yourself introduction xvii |
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 and then see how this affects the program the next time you run it finallytry to re-create the program yourself from scratch it doesn' have to be an exact copyyou can put your own spin on the program when copying the code from this bookyou don' necessarily have to type the comments (the text at the end of line following the symbol)as these are notes for human programmers and are ignored by python howevertry to write your python code on the same line numbers as the programs in this book to make comparison between the two easier if you have trouble finding typos in your programyou can compare your code to the code in this book with the online diff tool at bigbookpython/diffeach program has been given set of tags to describe itsuch as board gamesimulationartisticand two-player an explanation of each of these tags and cross-index of tags and projects can be found in appendix the projects are listed in alphabetical orderhowever downloading and installing python python is the name of both the programming language and the interpreter software that runs your python code the python software is completely free to download and use you can check if you already have python installed from command line window on windowsopen the command prompt program and then enter py --version if you see output like the followingthen python is installedc:\users\al>py --version python on macos and linuxopen the terminal program and then enter python --version if you see output like the followingthen python is installedpython --version python this book uses python version several backward-incompatible changes were made between python and and the programs in this book require at least python version (released in to run if you see an error message telling you that python cannot be found or the version reports python you can download the latest python installer for your xviii introduction |
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 you with an overwhelming number of advanced options open download the installer for your operating system and then run it by doubleclicking the installer file if you are on macosrunning the installer opens window where you must drag the mu icon to the applications folder icon to continue the installation if you are on ubuntuyou'll need to install mu as python package in that caseopen new terminal window and run pip install mu-editor to install and mu-editor to run it click the instructions button in the python package section of the download page for full instruction details running the mu editor once it' installedlet' start muon windows or laterclick the start icon in the lower-left corner of your screenenter mu in the search boxand select mu when it appears on macosopen the finder windowclick applicationsand then click mu-editor on ubuntupress ctrl-alt- to open terminal window and then enter python - mu the first time mu runsa select mode window appears with the following optionsadafruit circuitpythonbbc micro:bitpygame zeroand python select python you can always change the mode later by clicking the mode button at the top of the editor window you'll be able to enter the code into mu' main window and then saveopenand run your files from the buttons at the top running idle and other editors you can use any number of editors for writing python code the integrated development and learning environment (idlesoftware installs along with pythonand it can serve as second editor if for some reason you can' get mu installed or working let' start idle nowon windows or laterclick the start icon in the lower-left corner of your screenenter idle in the search boxand select idle (python guiintroduction xix |
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 click programming and python (idleyou can also select thonny python ide from under the programming menu there are several other free editors you can use to enter and run python codesuch asthonnya python ide for beginnersat pycharm community editiona python ide used by professional developersat installing python modules most of the programs in this book only require the python standard librarywhich is installed automatically with python howeversome programs require third-party modules such as pyperclipbextplaysoundand pyttsx all of these can be installed at once by installing the bigbookpython module for the mu editoryou must install the -alpha version (or lateras of you can find this version at the top of the download page at sion of musection after installationclick the gear icon in the lower-left corner of the window to bring up the mu administration window select the third party packages tabenter bigbookpython into the text fieldand click ok this installs all of the third-party modules used by the programs in this book for the visual studio code or idle editoropen the editor and run the following python code from the interactive shellimport ossys os system(sys executable - pip install --user bigbookpython' the number appears after the second instruction if everything worked correctly otherwiseif you see an error message or another numbertry running the following instructionswhich don' have the --user optionimport ossys os system(sys executable - pip install bigbookpython' xx introduction |
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 code in this book or copy and paste it to your computer take the time to enter the code into the editor for yourself open new file in your code editor and enter the code pay attention to the line numbers in this book and your editor to make sure you aren' accidentally skipping any lines if you encounter errorsuse the online diff tool at bigbookpython/diffto show you any differences between your code and the code in this book to get better understanding of these programstry running them under the debugger after entering the source code and running it few timestry making experimental changes to the code the comments marked with (!have suggestions for small changes you can makeand each project lists suggestions for larger modifications nexttry re-creating the program from scratch without looking at the source code in this book it doesn' have to be exactly the same as this programyou can invent your own versiononce you've worked through the programs in this bookyou might want to start creating your own most modern video games and software applications are complicatedrequiring teams of programmersartistsand designers to create howevermany boardcardand paper-and-pencil games are often simple enough to re-create as program many of these fall under the category of "abstract strategy games you can find list of them at running programs from the terminal the programming projects in this book that use the bext module have colorful text for their output howeverthese colors won' appear when you run them from muidleor other editors these programs should be run from terminalalso called command linewindow on windowsrun the command prompt program from the start menu on macosrun terminal from spotlight on ubuntu linuxrun terminal from ubuntu dash or press ctrl-alt- when the terminal window appearsyou should change the current directory to the folder with your py files with the cd (change directorycommand (directory is another term for folder for exampleif were on windows and saved my python programs to the :\users\al folderi would enter the following line introduction xxi |
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 take guess --snip-you can terminate programs run from the terminal by pressing ctrlc rather than close the terminal window itself running programs from phone or tablet ideally you'll have laptop or desktop computer with full keyboard to write codeas tapping on phone or even tablet keyboard can be tedious while there are no established python interpreters for android or iosthere are websites that host online python interactive shells you can use from web browser these will also work for laptops and desktopsin case you're an instructor who doesn' have account permission to install new software on your classroom' computers the websites where comhave python interpreters that are free to use in your web browser these websites will work with most of the projects in this book howeverthey won' work with programs that make use of third-party modulessuch as bextpyperclippyttsx and playsound they also won' work with programs that need to read or write files with the open(function if you see these terms in the program' codethe program won' work in these online python interpreters howeverthe majority of programs in this book will work just fine how to get help unless you can hire private tutor or have programmer friend who can answer your programming questionsyou'll need to rely on yourself to find answers to your questions fortunatelyyour questions have almost certainly been asked before being able to find answers on your own is an important skill for programmers to learn don' feel discouraged if you find yourself constantly looking up answers to your programming questions online you may feel like it' "cheatingto check online instead of memorizing everything about programming from xxii introduction |
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 of code the error occurred on here' an example of program that had an error while calculating how many slices of pizza each person should gettraceback (most recent call last)file "pizza py"line in print('each person gets'(slices people)slices of pizza 'zerodivisionerrordivision by zero from this tracebackyou might not realize that the problem is that the people variable is set to and so the expression slices people caused zero-divide error error messages are often so short they're not even full sentences since programmers encounter them regularlythey're intended as reminders rather than full explanations if you're encountering an error message for the first timecopying and pasting it into an internet search often returns detailed explanation of what the error means and what its likely causes are if you're unable to find the solution to your problem by searching the internetyou can post your question to an online forum or email someone to make this process as efficient as possibleask specificwell-stated questions this means providing full source code and error message detailsexplaining what you've already triedand telling your helper what operating system and version of python you're using not only will the posted answers solve your problembut they can help future programmers who have your same question and find your post typing code you don' have to be able to type fast to be programmerbut it helps while many people take "hunt and peckapproach to typinga faster typing speed can make programming less of chore as you work through the programs in this bookyou'll want your eyes on the code and not on your keyboard there are free websites for learning how to typesuch as club comor keyboard and transparent hands on the screen so you can practice without the bad habit of looking down at the keyboard to find keys like every skilltyping is matter of practiceand writing code can provide you with plenty of opportunities to type keyboard shortcuts allow you to perform actions in fraction of the time it takes to move the mouse to menu and perform the action shortcut is often written like "ctrl- ,which means pressing down one of the introduction xxiii |
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 keyboard shortcuts other shortcuts are not so obvious for examplealt-tab on windows and linux and command-tab on macos allow you to switch focus to another application' window you can hold the alt or command key down and repeatedly press tab to select specific window to switch to copying and pasting the clipboard is feature of your operating system that can temporarily store data for pasting while this data can be textimagesfilesor other types of informationwe'll be dealing with text data in this section copying text places copy of the currently selected text onto the clipboard pasting text enters the text on the clipboard into wherever the text cursor currently isas though you had instantly typed it yourself copying and pasting text frees you from having to retype text that already exists on your computerwhether it' single line or hundreds of pages to copy and paste textfirst selector highlightthe text to copy you can do this by holding down the primary mouse button (which is the left buttonif the mouse is set for right-handed usersand dragging over the text to select it howeverholding down the shift key and moving the cursor with the keyboard shortcuts is often faster and more precise many applications allow you to double-click word to immediately select the entire word you can also often triple-click to immediately select an entire line or paragraph the next step is to press ctrl- on windows or command- on macos to copy the selected text to the clipboard the clipboard can only hold one selection of textso copying text replaces anything that was previously on the clipboard finallymove the cursor to where you want the text to appear and press ctrl- on windows or command- on macos to paste the text you can paste as many times as you wantthe text remains on the clipboard until you copy new text to replace it finding and replacing text dan russella search anthropologist at googleexplained in atlantic article that when he studied people' computer usage habits percent of them didn' know they could press ctrl- (on windows and linuxor command- (on macosto search for words in their applications this is an incredibly useful featurenot just in code editorsbut in word processorsweb browsersspreadsheet applicationsand almost every kind xxiv introduction |
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 ctrl- or command- shortcut this allows you to locate occurrences of one bit of text and replace it with another this is useful if you want to rename variable or function howeveryou need to be careful using the find-and-replace feature because you could unintentionally replace text that matched your find criteria by coincidence the debugger debugger is tool that runs programs one line at time and lets you inspect the current state of the program' variables it' valuable tool for tracking down bugs this section will explain the features of the mu editor' debugger don' worryevery debugger will have these same featureseven if the user interface looks different to start program in the debuggeruse the debug menu item in your ide instead of the run menu item the debugger will start in paused state on the first line of your program all debuggers have the following buttonscontinuestep instep overstep outand stop clicking the continue button causes the program to execute normally until it terminates or reaches breakpoint ( describe breakpoints later in this section if you are done debugging and want the program to continue normallyclick the continue button clicking the step in button causes the debugger to execute the next line of code and then pause again if the next line of code is function callthe debugger will "step intothat function and jump to the first line of code of that function clicking the step over button executes the next line of codesimilar to the step in button howeverif the next line of code is function callthe step over button will "step overthe code in the function the function' code executes at full speedand the debugger will pause as soon as the function call returns using the step over button is more common than using the step in button clicking the step out button causes the debugger to execute lines of code at full speed until it returns from the current function if you have stepped into function call with the step in button and now simply want to keep executing instructions until you get back outclick the step out button to "step outof the current function call if you want to stop debugging entirely and not bother to continue executing the rest of the programclick the stop button the stop button immediately terminates the program you can set breakpoint on particular line and let the program run at normal speed until it reaches the breakpoint line at that pointthe introduction xxv |
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 debugging can often be slower than using debugger with print debuggingyou must add the print(callsrerun your programand then remove the print(calls later howeverafter rerunning the programyou'll often find that you need to add more print(calls to see the values of other variables this means you need to rerun the program yet againand this run could reveal that you need another round of adding print(callsand so on alsoit' common to forget some of the print(calls you've addedrequiring an additional round of deleting print(calls print debugging is straightforward for simple bugsbut using an actual debugger can save you time in the long run summary programming is funcreative skill to develop whether you've mastered the basics of python syntax or simply want to dive into some real python programsthe projects in this book will spark new ideas for what' possible with as little as few pages of code the best way to work through these programs isn' to merely read their code or copy and paste it to your computer take the time to manually type the code from this book into your editor to develop the muscle memory of writing code this also slows you down so you can consider each line as you typeinstead of merely skimming it over with your eyes look up any instructions you don' recognize using an internet search engineor experiment with them in the interactive shell finallytake it upon yourself to re-create the program from scratch and then modify it with features of your own these exercises give you solid foundation for how programming concepts are applied to create actualrunnable programs and most of alldon' forget to have funxxvi introduction |
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 digits you have tries to guess the secret number |
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 bagels no digit is correct have thought up number you have guesses to get it guess # pico guess # bagels guess # pico pico --snip-guess # fermi fermi guess # you got itdo you want to play again(yes or nono thanks for playinghow it works keep in mind that this program uses not integer values but rather string values that contain numeric digits for example' is different value than we need to do this because we are performing string comparisons with the secret numbernot math operations remember that ' can be leading digitthe string ' is different from ' 'but the integer is the same as """bagelsby al sweigart al@inventwithpython com deductive logic game where you must guess number based on clues view this code at version of this game is featured in the book "invent your own computer games with python tagsshortgamepuzzle"" import random project # |
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 correct and in the right position bagels no digit is correct for exampleif the secret number was and your guess was the clues would be fermi pico ''format(num_digits) while truemain game loop this stores the secret number the player needs to guess secretnum getsecretnum( print(' have thought up number ' print(you have {guesses to get it format(max_guesses) numguesses while numguesses <max_guesses guess ' keep looping until they enter valid guess while len(guess!num_digits or not guess isdecimal() print('guess #{}format(numguesses) guess input('' clues getclues(guesssecretnum print(clues numguesses + if guess =secretnum break they're correctso break out of this loop if numguesses max_guesses print('you ran out of guesses ' print('the answer was {format(secretnum) ask player if they want to play again print('do you want to play again(yes or no)' if not input(''lower(startswith(' ') break print('thanks for playing!' def getsecretnum() """returns string made up of num_digits unique random digits "" numbers list(' 'create list of digits to random shuffle(numbersshuffle them into random order get the first num_digits digits in the list for the secret numberbagels |
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 correct place clues append('fermi' elif guess[iin secretnum correct digit is in the incorrect place clues append('pico' if len(clues= return 'bagelsthere are no correct digits at all else sort the clues into alphabetical order so their original order doesn' give information away clues sort( make single string from the list of string clues return join(clues if the program is run (instead of imported)run the game if __name__ ='__main__' main(after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingchange the number of digits for the secret number by changing num_digits change the number of guesses the player gets by changing max_guesses try to create version with letters as well as digits in the secret number exploring the program 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 when you change the num_digits constant project # |
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 comment out if guess =secretnumon line and return 'you got it!on line what happens if you comment out numguesses + on line bagels |
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 birthday this program performs several probability experiments to determine the percentages for groups of different sizes we call these types of experimentsin which we conduct multiple random trials to understand the likely outcomesmonte carlo experiments you can find out more about the birthday paradox at org/wiki/birthday_problem |
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 on jul generating random birthdays , times press enter to begin let' run another , simulations simulations run simulations run --snip- simulations run simulations run out of , simulations of peoplethere was matching birthday in that group times this means that people have chance of having matching birthday in their group that' probably more than you would thinkhow it works running , simulations can take whilewhich is why lines and report that another , simulations have finished this feedback can assure the user that the program hasn' frozen notice that some of the integerslike on line and on lines and have underscores these underscores have no special meaningbut python allows them so that programmers can make integer values easier to read in other wordsit' easier to read "one hundred thousandfrom than from """birthday paradox simulationby al sweigart al@inventwithpython com explore the surprising probabilities of the "birthday paradox more info at view this code at tagsshortmathsimulation"" import datetimerandom def getbirthdays(numberofbirthdays) """returns list of number random date objects for birthdays "" birthdays [birthday paradox |
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 getmatch(birthdays) """returns the date object of birthday that occurs more than once in the birthdays list "" if len(birthdays=len(set(birthdays)) return none all birthdays are uniqueso return none compare each birthday to every other birthday for abirthdaya in enumerate(birthdays) for bbirthdayb in enumerate(birthdays[ :]) if birthdaya =birthdayb return birthdaya return the matching birthday display the intro print('''birthday paradoxby al sweigart al@inventwithpython com the birthday paradox shows us that in group of peoplethe odds that two of them have matching birthdays is surprisingly large this program does monte carlo simulation (that isrepeated random simulationsto explore this concept (it' not actually paradoxit' just surprising result ''' set up tuple of month names in order months ('jan''feb''mar''apr''may''jun' 'jul''aug''sep''oct''nov''dec' while truekeep asking until the user enters valid amount print('how many birthdays shall generate(max )' response input('' if response isdecimal(and ( int(response< ) numbdays int(response break user has entered valid amount print( generate and display the birthdays print('here are'numbdays'birthdays:' birthdays getbirthdays(numbdays for ibirthday in enumerate(birthdays) if ! display comma for each birthday after the first birthday print(''end='' project # |
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 print('multiple people have birthday on'datetext else print('there are no matching birthdays ' print( run through , simulations print('generating'numbdays'random birthdays , times ' input('press enter to begin ' print('let\' run another , simulations ' simmatch how many simulations had matching birthdays in them for in range( ) report on the progress every , simulations if = print( 'simulations run ' birthdays getbirthdays(numbdays if getmatch(birthdays!none simmatch simmatch print(' , simulations run ' display simulation results probability round(simmatch print('out of , simulations of'numbdays'peoplethere was ' print('matching birthday in that group'simmatch'times this means' print('that'numbdays'people have 'probability'chance of' print('having matching birthday in their group ' print('that\' probably more than you would think!'exploring the program 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 how are birthdays represented in this program(hintlook at line how could you remove the maximum limit of birthdays the program generatesbirthday paradox |
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 resembles world mapbut you can change this to any image you' like the binary simplicity of the space-ormessage-characters system makes it good for beginners try experimenting with different messages to see what the results look like |
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!hello!hello!hello!hello el lo!hello!hello!he lo!hello!hello!hello!hello!hel !hello!hello lo lo! ll !hello!hello! !hello!he llo!hel hello!hello!hell hello!he ello!hello!hello!hello!hell lloell ello!hello!hell !hello el lo! ello!hello!hell ell !he !hello llo!hello!hel el he !hello! lo!hello!hell ! llo ello!hel hello!he llo hell ello!hell ello! hell ! oello!hell ello! ! lo!hel elloel !hel lo!he lloe llo!hell llo! llollo!hello lloll lo!hell llo ll hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!he how it works instead of individually typing each character of the world map patternyou can copy and paste the whole thing from world txt line of periods at the top and bottom of the pattern acts as ruler to help you align it correctly howeverthe program will still work if you make typos in the pattern the bitmap splitlines(method call on line returns list of stringseach of which is line in the multiline bitmap string using multiline string makes the bitmap easier to edit into whatever pattern you like the program fills in any non-space character in the patternwhich is why asterisksperiodsor any other character do the same thing the message[ len(message)code on line causes the repetition of the text in message as increases from to number larger than len(message)the expression len(messageevaluates to again this causes message[ len(message)to repeat the characters in message as increases """bitmap messageby al sweigart al@inventwithpython com displays text message according to the provided bitmap image view this code at project # |
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 "" ********************************************* *************************************************** ********************************************** ****************************** ***************************** ********************************* ************************* ********************* ******************* ********************** ******************* ****************** *************** ************** ************** *************** ********** ** * "" print('bitmap messageby al sweigart al@inventwithpython com' print('enter the message to display with the bitmap ' message input('' if message ='' sys exit( loop over each line in the bitmap for line in bitmap splitlines() loop over each character in the line for ibit in enumerate(line) if bit =' print an empty space since there' space in the bitmap print('end='' else print character from the message print(message[ len(message)]end='' print(print newline after entering the source code and running it few timestry making experimental changes to it you can change the string in bitmap to create entirely new patterns bitmap message |
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 created on line represent what bug happens if you delete or comment out print(on line project # |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.