id
int64
0
25.6k
text
stringlengths
0
4.59k
9,100
introduction to gui programming when gui program is run it normally begins by creating its main window and all of the main window' widgetssuch as the menu bartoolbarsthe central areaand the status bar once the window has been createdlike server programthe gui program simply waits whereas server waits for client programs to connect to ita gui program waits for user interaction such as mouse clicks and key presses this is illustrated in contrast to console programs in figure the gui program does not wait passivelyit runs an event loopwhich in pseudocode looks like thiswhile trueevent getnextevent(if eventif event =terminatebreak processevent(eventwhen the user interacts with the programor when certain other things occursuch as timer timing out or the program' window being activated (maybe because another program was closed)an event is generated inside the gui library and added to the event queue the program' event loop continuously checks to see whether there is an event to processand if there isit processes it (or passes it on to the event' associated function or method for processingas gui programmers we can rely on the gui library to provide the event loop our responsibility is to create classes that represent the windows and widgets our program needs and to provide them with methods that respond appropriately to user interactions dialog-style programs ||the first program we will look at is the interest program this is dialog-style program ( it has no menus)which the user can use to perform compound interest calculations the program is shown in figure in most object-oriented gui programsa custom class is used to represent single main window or dialogwith most of the widgets it contains being instances of standard widgetssuch as buttons or checkboxessupplied by the library like most cross-platform gui librariestk doesn' really make distinction between window and widget-- window is simply widget that has no widget parent ( it is not contained inside another widgetwidgets that don' have widget parent (windowsare automatically supplied with frame and window decorations (such as title bar and close button)and they usually contains other widgets most widgets are created as children of another widget (and are contained inside their parent)whereas windows are created as children of the tkinter tk
9,101
figure the interest program object--an object that conceptually represents the applicationand something we will return to later on in addition to distinguishing between widgets and windows (also called top-level widgets)the parent-child relationships help ensure that widgets are deleted in the right order and that child widgets are automatically deleted when their parent is deleted the initializer is where the user interface is created (the widgets added and laid outthe mouse and keyboard bindings made)and the other methods are used to respond to user interactions tk allows us to create custom widgets either by subclassing predefined widget such as tkinter frameor by creating an ordinary class and adding widgets to it as attributes here we have used subclassing--in the next example we will show both approaches since the interest program has just one main window it is implemented in single class we will start by looking at the class' initializerbroken into five parts since it is rather long class mainwindow(tkinter frame)def __init__(selfparent)super(__init__(parentself parent parent self grid(row= column= we begin by initializing the base classand we keep copy of the parent for later use rather than using absolute positions and sizeswidgets are laid out inside other widgets using layout managers the call to grid(lays out the frame using the grid layout manager every widget that is shown must be laid outeven top-level ones tk has several layout managersbut the grid is the easiest to understand and usealthough for top-level layouts where there is only one widget to lay out we could use the packer layout manager by calling pack(instead of grid(row= column= to achieve the same effect self principal tkinter doublevar(self principal set(
9,102
introduction to gui programming self rate tkinter doublevar(self rate set( self years tkinter intvar(self amount tkinter stringvar(tk allows us to create variables that are associated with widgets if variable' value is changed programmaticallythe change is reflected in its associated widgetand similarlyif the user changes the value in the widget the associated variable' value is changed here we have created two "doublevariables (these hold float values)an integer variableand string variableand have set initial values for two of them principallabel tkinter label(selftext="principal $:"anchor=tkinter wunderline= principalscale tkinter scale(selfvariable=self principalcommand=self updateuifrom_= to= resolution= orient=tkinter horizontalratelabel tkinter label(selftext="rate %:"underline= anchor=tkinter wratescale tkinter scale(selfvariable=self ratecommand=self updateuifrom_= to= resolution= digits= orient=tkinter horizontalyearslabel tkinter label(selftext="years:"underline= anchor=tkinter wyearsscale tkinter scale(selfvariable=self yearscommand=self updateuifrom_= to= orient=tkinter horizontalamountlabel tkinter label(selftext="amount $"anchor=tkinter wactualamountlabel tkinter label(selftextvariable=self amountrelief=tkinter sunkenanchor=tkinter ethis part of the initializer is where we create the widgets the tkinter label widget is used to display read-only text to the user like all widgets it is created with parent (in this case--and as usual--the parent is the containing widget)and then keyword arguments are used to set various other aspects of the widget' behavior and appearance we have set the principallabel' text appropriatelyand set its anchor to tkinter wwhich means that the label' text is aligned west (leftthe underline parameter is used to specify which character in the label should be underlined to indicate keyboard accelerator ( alt+ )further on we will see how to make the accelerator work ( keyboard accelerator is key sequence of the form alt+letter where letter is an underlined letter and which results in the keyboard focus being switched to the widget associated with the acceleratormost commonly the widget to the right or below the label that has the accelerator
9,103
for the tkinter scale widgets we give them parent of self as usualand associate variable with each one in additionwe give function (or in this case methodobject reference as their command--this method will be called automatically whenever the scale' value is changedand set its minimum (from_with trailing underscore since plain from is keywordand maximum (tovaluesand horizontal orientation for some of the scales we set resolution (step sizeand for the ratescale the number of digits it must be able to display the actualamountlabel is also associated with variable so that we can easily change the text the label displays later on we have also given this label sunken relief so that it fits in better visually with the scales principallabel grid(row= column= padx= pady= sticky=tkinter wprincipalscale grid(row= column= padx= pady= sticky=tkinter ewratelabel grid(row= column= padx= pady= sticky=tkinter wratescale grid(row= column= padx= pady= sticky=tkinter ewyearslabel grid(row= column= padx= pady= sticky=tkinter wyearsscale grid(row= column= padx= pady= sticky=tkinter ewamountlabel grid(row= column= padx= pady= sticky=tkinter wactualamountlabel grid(row= column= padx= pady= sticky=tkinter ewhaving created the widgetswe must now lay them out the grid layout we have used is illustrated in figure principallabel principalscale ratelabel ratescale yearslabel yearsscale amountlabel actualamountlabel figure the interest program' layout every widget supports the grid(method (and some other layout methods such as pack()calling grid(lays out the widget within its parentmaking it occupy the specified row and column we can set widgets to span multiple columns and multiple rows using additional keyword arguments (rowspan and columnspan)and we can add some margin around them using the padx (left and
9,104
introduction to gui programming right marginand pady (top and bottom marginkeyword arguments giving integer pixel amounts as arguments if widget is allocated more space than it needsthe sticky option is used to determine what should be done with the spaceif not specified the widget will occupy the middle of its allocated space we have set all of the first column' labels to be sticky tkinter (westand all of the second column' widgets to be sticky tkinter ew (east and west)which makes them stretch to fill the entire width available to them all of the widgets are held in local variablesbut they don' get scheduled for garbage collection because the parent-child relationships ensure that they are not deleted when they go out of scope at the end of the initializersince all of them have the main window as their parent sometimes widgets are created as instance variablesfor exampleif we need to refer to them outside the initializerbut in this case we used instance variables for the variables associated with the widgets (self principalself rateand self years)so it is these we will use outside the initializer principalscale focus_set(self updateui(parent bind(""lambda *ignoreprincipalscale focus_set()parent bind(""lambda *ignoreratescale focus_set()parent bind(""lambda *ignoreyearsscale focus_set()parent bind(""self quitparent bind(""self quitat the end of the initializer we give the keyboard focus to the principalscale widget so that as soon as the program starts the user is able to set the initial amount of money we then call the self updateui(method to calculate the initial amount nextwe set up few key bindings (unfortunatelybinding has three different meanings--variable binding is where namethat isan object referenceis bound to an objecta key binding is where keyboard action such as key press or release is associated with function or method to call when the action occursand bindings for library is the glue code that makes library written in language other than python available to python programmers through python modules key bindings are essential for some disabled users who have difficulty with or are unable to use the mouseand they are great convenience for fast typists who want to avoid using the mouse because it slows them down the first three key bindings are used to move the keyboard focus to scale widget for examplethe principallabel' text is set to principal $and its underline to so the label appears as principal $:and with the first keyboard binding in place when the user types alt+ the keyboard focus will switch to the principlescale widget the same applies to the other two bindings note that we do not bind the focus_set(method directly this is because when functions or methods are called as the result of an event binding they are given the event
9,105
that invoked them as their first argumentand we don' want this event sowe use lambda function that accepts but ignores the event and calls the method without the unwanted argument we have also created two keyboard shortcuts--these are key combinations that invoke particular action here we have set ctrl+ and esc and bound them both to the self quit(method that cleanly terminates the program it is possible to create keyboard bindings for individual widgetsbut here we have set them all on the parent (the application)so they all work no matter where the keyboard focus is tk' bind(method can be used to bind both mouse clicks and key pressesand also programmer-defined events special keys like ctrl and esc have tk-specific names (control and escape)and ordinary letters stand for themselves key sequences are created by putting the parts in angle brackets and separating them with hyphens having created and laid out the widgetsand set up the key bindingsthe appearance and basic behavior of the program are in place now we will review the methods that respond to user actions to complete the implementation of the program' behavior def updateui(self*ignore)amount self principal get(( (self rate get( )*self years get()self amount set("{ }format(amount)this method is called whenever the user changes the principalthe rateor the years since it is the command associated with each of the scales all it does is retrieve the value from each scale' associated variableperform the compound interest calculationand store the result (as stringin the variable associated with the actual amount label as resultthe actual amount label always shows an up-to-date amount def quit(selfevent=none)self parent destroy(if the user chooses to quit (by pressing ctrl+ or escor by clicking the window' close buttonthis method is called since there is no data to save we just tell the parent (which is the application objectto destroy itself the parent will destroy all of its children--all of the windowswhich in turn will destroy all of their widgets--so clean termination takes place application tkinter tk(path os path join(os path dirname(__file__)"images/"if sys platform startswith("win")icon path "interest ico
9,106
introduction to gui programming elseicon "@path "interest xbmapplication iconbitmap(iconapplication title("interest"window mainwindow(applicationapplication protocol("wm_delete_window"window quitapplication mainloop(after defining the class for the main (and in this case onlywindowwe have the code that starts the program running we begin by creating an object to represent the application as whole to give the program an icon on windows we use an ico file and pass the name of the file (with its full pathto the iconbitmap(method but for unix platforms we must provide bitmap ( monochrome imagetk has several built-in bitmapsso to distinguish one that comes from the file system we must precede its name with an symbol next we give the application title (which will appear in the title bar)and then we create an instance of our mainwindow class giving the application object as its parent at the end we call the protocol(method to say what should happen if the user clicks the close button--we have said that the mainwindow quit(method should be calledand finally we start the event loop--it is only when we reach this point that the window is displayed and is able to respond to user interactions main-window-style programs ||although dialog-style programs are often sufficient for simple tasksas the range of functionality program offers grows it often makes sense to create complete main-window-style application with menus and toolbars such applications are usually easier to extend than dialog-style programs since we can add extra menus or menu options and toolbar buttons without affecting the main window' layout in this section we will review the bookmarks-tk pyw program shown in figure the program maintains set of bookmarks as pairs of (nameurlstrings and has facilities for the user to addeditand remove bookmarksand to open their web browser at particular bookmarked web page the program has two windowsthe main window with the menu bartoolbarlist of bookmarksand status barand dialog window for adding or editing bookmarks creating main window |the main window is similar to dialog in that it has widgets that must be created and laid out and in addition we must add the menu barmenustoolbarand status baras well as methods to perform the actions the user requests
9,107
figure the bookmarks program the user interface is all set up in the main window' initializerwhich we will review in five parts because it is fairly long class mainwindowdef __init__(selfparent)self parent parent self filename none self dirty false self data {menubar tkinter menu(self parentself parent["menu"menubar for this windowinstead of inheriting widget as we did in the preceding examplewe have just created normal python class if we inherit we can reimplement the methods of the class we have inheritedbut if we don' need to do that we can simply use composition as we have done here the appearance is provided by creating widget instance variablesall contained within tkinter frame as we will see in moment we need to keep track of four pieces of informationthe parent (applicationobjectthe name of the current bookmarks filea dirty flag (if true this means that changes have been made to the data that have not been saved to disk)and the data itselfa dictionary whose keys are bookmark names and whose values are urls to create menu bar we must create tkinter menu object whose parent is the window' parentand we must tell the parent that it has menu (it may seem strange that menu bar is menubut tk has had very long evolution which
9,108
introduction to gui programming has left it with some odd corners menu bars created like this do not need to be laid outtk will do that for us filemenu tkinter menu(menubarfor labelcommandshortcut_textshortcut in ("new "self filenew"ctrl+ """)("open "self fileopen"ctrl+ """)("save"self filesave"ctrl+ """)(nonenonenonenone)("quit"self filequit"ctrl+ """))if label is nonefilemenu add_separator(elsefilemenu add_command(label=labelunderline= command=commandaccelerator=shortcut_textself parent bind(shortcutcommandmenubar add_cascade(label="file"menu=filemenuunderline= each menu bar menu is created in the same way first we create tkinter menu object that is child of the menu barand then we add separators or commands to the menu (note that an accelerator in tk terminology is actually keyboard shortcutand that all the accelerator option sets is the text of the shortcutit does not actually set up key binding the underline indicates which character is underlinedin this case the first one of every menu optionand this letter becomes the menu option' keyboard accelerator in addition to adding menu option (called command)we also provide keyboard shortcut by binding key sequence to the same command as that invoked when the corresponding menu option is chosen at the end the menu is added to the menu bar using the add_cascade(method we have omitted the edit menu since it is structurally identical to the file menu' code frame tkinter frame(self parentself toolbar_images [toolbar tkinter frame(framefor imagecommand in ("images/filenew gif"self filenew)("images/fileopen gif"self fileopen)("images/filesave gif"self filesave)("images/editadd gif"self editadd)("images/editedit gif"self editedit)("images/editdelete gif"self editdelete)("images/editshowwebpage gif"self editshowwebpage))image os path join(os path dirname(__file__)imagetry
9,109
image tkinter photoimage(file=imageself toolbar_images append(imagebutton tkinter button(toolbarimage=imagecommand=commandbutton grid(row= column=len(self toolbar_images- except tkinter tclerror as errprint(errtoolbar grid(row= column= columnspan= sticky=tkinter nwwe begin by creating frame in which all of the window' widgets will be contained then we create another frametoolbarto contain horizontal row of buttons that have images instead of textsto serve as toolbar buttons we lay out each toolbar button one after the other in grid that has one row and as many columns as there are buttons at the end we lay out the toolbar frame itself as the main window frame' first rowmaking it north west sticky so that it will always cling to the top left of the window (tk automatically puts the menu bar above all the widgets laid out in the window the layout is illustrated in figure with the menu bar laid out by tk shown with white backgroundand our layouts shown with gray backgrounds menubar toolbar self listbox scrollbar self statusbar figure the bookmarks program' main window layouts when an image is added to button it is added as weak referenceso once the image goes out of scope it is scheduled for garbage collection we must avoid this because we want the buttons to show their images after the initializer has finishedso we create an instance variableself toolbar_imagessimply to hold references to the images to keep them alive for the program' lifetime out of the boxtk can read only few image file formatsso we have had to use gif images if any image is not found tkinter tclerror exception is raisedso we must be careful to catch this to avoid the program terminating just because of missing image notice that we have not made all of the actions available from the menus available as toolbar buttons--this is common practice if the python imaging library' tk extension is installedall of the modern image formats become supported see www pythonware com/products/pilfor details
9,110
introduction to gui programming scrollbar tkinter scrollbar(frameorient=tkinter verticalself listbox tkinter listbox(frameyscrollcommand=scrollbar setself listbox grid(row= column= sticky=tkinter nsewself listbox focus_set(scrollbar["command"self listbox yview scrollbar grid(row= column= sticky=tkinter nsself statusbar tkinter label(frametext="ready "anchor=tkinter wself statusbar after( self clearstatusbarself statusbar grid(row= column= columnspan= sticky=tkinter ewframe grid(row= column= sticky=tkinter nsewthe main window' central area (the area between the toolbar and the status baris occupied by list box and an associated scrollbar the list box is laid out to be sticky in all directionsand the scrollbar is sticky only north and south (verticallyboth widgets are added to the window frame' gridside by side we must ensure that if the user scrolls the list box by tabbing into it and using the up and down arrow keysor if they scroll the scrollbarboth widgets are kept in sync this is achieved by setting the list box' yscrollcommand to the scrollbar' set(method (so that user navigation in the list box results in the scrollbar being moved if necessary)and by setting the scrollbar' command to the listbox' yview(method (so that scrollbar movements result in the list box being moved correspondinglythe status bar is just label the after(method is single shot timer ( timer that times out once after the given intervalwhose first argument is timeout in milliseconds and whose second argument is function or method to call when the timeout is reached this means that when the program starts up the status bar will show the text "ready for five secondsand then the status bar will be cleared the status bar is laid out as the last row and is made sticky west and east (horizontallyat the end we lay out the window' frame itself we have now completed the creation and layout of the main window' widgetsbut as things stand the widgets will assume fixed default sizeand if the window is resized the widgets will not change size to shrink or grow to fit the next piece of code solves this problem and completes the initializer frame columnconfigure( weight= frame columnconfigure( weight= frame rowconfigure( weight= frame rowconfigure( weight= frame rowconfigure( weight=
9,111
window self parent winfo_toplevel(window columnconfigure( weight= window rowconfigure( weight= self parent geometry("{ } { }+{ }+{ }format( )self parent title("bookmarks unnamed"the columnconfigure(and rowconfigure(methods allow us to give weightings to grid we begin with the window framegiving all the weight to the first column and the second row (which is occupied by the list box)so if the frame is resized any excess space is given to the list box on its own this is not sufficientwe must also make the top-level window that contains the frame resizableand we do this by getting reference to the window using the wininfo_toplevel(methodand then making the window resizable by setting its row and column weights to at the end of the initializer we set an initial window size and position using string of the form widthxheight+ + (if we wanted to set only the size we could use the form widthxheight instead finallywe set the window' titlethereby completing the window' user interface if the user clicks toolbar button or chooses menu option method is called to carry out the required action and some of these methods rely on helper methods we will now review all the methods in turnstarting with one that is called five seconds after the program starts def clearstatusbar(self)self statusbar["text""the status bar is simple tkinter label we could have used lambda expression in the after(method call to clear itbut since we need to clear the status bar from more than one place we have created method to do it def filenew(self*ignore)if not self okaytocontinue()return self listbox delete( tkinter endself dirty false self filename none self data {self parent title("bookmarks unnamed"if the user wants to create new bookmarks file we must first give them the chance to save any unsaved changes in the existing file if there is one this is factored out into the mainwindow okaytocontinue(method since it is used in few different places the method returns true if it is okay to continueand false otherwise if continuingwe clear the list box by deleting all its entries
9,112
introduction to gui programming from the first to the last--tkinter end is constant used to signify the last item in contexts where widget can contain multiple items then we clear the dirty flagfilenameand datasince the file is new and unchangedand we set the window title to reflect the fact that we have new but unsaved file the ignore variable holds sequence of zero or more positional arguments that we don' care about in the case of methods invoked as result of menu options choices or toolbar button presses there are no ignored argumentsbut if keyboard shortcut is used ( ctrl+ )then the invoking event is passedand since we don' care how the user invoked the actionwe ignore the event that requested it def okaytocontinue(self)if not self dirtyreturn true reply tkinter messagebox askyesnocancel"bookmarks unsaved changes""save unsaved changes?"parent=self parentif reply is nonereturn false if replyreturn self filesave(return true if the user wants to perform an action that will clear the list box (creating or opening new filefor example)we must give them chance to save any unsaved changes if the file isn' dirty there are no changes to saveso we return true right away otherwisewe pop up standard message box with yesnoand cancel buttons if the user cancels the reply is nonewe take this to mean that they don' want to continue the action they started and don' want to saveso we just return false if the user says yesreply is trueso we give them the chance to save and return true if they saved and false otherwise and if the user says noreply is falsetelling us not to savebut we still return true because they want to continue the action they startedabandoning their unsaved changes tk' standard dialogs are not imported by import tkinterso in addition to that import we must do import tkinter messageboxand for the following methodimport tkinter filedialog on windows and mac os the standard native dialogs are usedwhereas on other platforms tk-specific dialogs are used we always give the parent to standard dialogs since this ensures that they are automatically centered over the parent window when they pop up all the standard dialogs are modalwhich means that once one pops upit is the only window in the program that the user can interact withso they must close it (by clicking okopencancelor similar buttonbefore they can interact with the rest of the program modal dialogs are easiest for programmers to
9,113
work with since the user cannot change the program' state behind the dialog' backand because they block until they are closed the blocking means that when we create or invoke modal dialog the statement that follows will be executed only when the dialog is closed def filesave(self*ignore)if self filename is nonefilename tkinter filedialog asksaveasfilenametitle="bookmarks save file"initialdir="filetypes=[("bookmarks files""bmf")]defaultextension=bmf"parent=self parentif not filenamereturn false self filename filename if not self filename endswith(bmf")self filename +bmftrywith open(self filename"wb"as fhpickle dump(self datafhpickle highest_protocolself dirty false self setstatusbar("saved { items to { }formatlen(self data)self filename)self parent title("bookmarks { }formatos path basename(self filename))except (environmenterrorpickle pickleerroras errtkinter messagebox showwarning("bookmarks error""failed to save { }:\ { }formatself filenameerr)parent=self parentreturn true if there is no current file we must ask the user to choose filename if they cancel we return false to indicate that the entire operation should be cancelled otherwisewe make sure that the given filename has the right extension using the existing or new filename we save the pickled self data dictionary into the file after saving the bookmarks we clear the dirty flag since there are now no unsaved changesand put message on the status bar (which will time out as we will see in moment)and we update the window' title bar to include the filename (without the pathif we could not save the filewe pop up warning message box (which will automatically have an ok buttonto inform the user def setstatusbar(selftexttimeout= )self statusbar["text"text if timeout
9,114
introduction to gui programming self statusbar after(timeoutself clearstatusbarthis method sets the status bar label' textand if there is timeout ( fivesecond timeout is the default)the method sets up single shot timer to clear the status bar after the timeout period def fileopen(self*ignore)if not self okaytocontinue()return dir (os path dirname(self filenameif self filename is not none else "filename tkinter filedialog askopenfilenametitle="bookmarks open file"initialdir=dirfiletypes=[("bookmarks files""bmf")]defaultextension=bmf"parent=self parentif filenameself loadfile(filenamethis method starts off the same as mainwindow filenew(to give the user the chance to save any unsaved changes or to cancel the file open action if the user chooses to continue we want to give them sensible starting directoryso we use the directory of the current file if there is oneand the current working directory otherwise the filetypes argument is list of (descriptionwildcard -tuples that the file dialog should show if the user chose filenamewe set the current filename to the one they chose and call the loadfile(method to do the actual file reading separating out the loadfile(method is common practice to make it easier to load file without having to prompt the user for examplesome programs load the last used file at start-upand some programs have recently used files listed in menu so that when the user chooses one the loadfile(method is called directly with the menu option' associated filename def loadfile(selffilename)self filename filename self listbox delete( tkinter endself dirty false trywith open(self filename"rb"as fhself data pickle load(fhfor name in sorted(self datakey=str lower)self listbox insert(tkinter endnameself setstatusbar("loaded { bookmarks from { }formatself listbox size()self filename)self parent title("bookmarks { }formatos path basename(self filename))
9,115
except (environmenterrorpickle pickleerroras errtkinter messagebox showwarning("bookmarks error""failed to load { }:\ { }formatself filenameerr)parent=self parentwhen this method is called we know that any unsaved changes have been saved or abandonedso we are free to clear the list box we set the current filename to the one passed inclear the list box and the dirty flagand then attempt to open the file and unpickle it into the self data dictionary once we have the data we iterate over all the bookmark names and append each one to the list box finallywe give an informative message in the status bar and update the window' title bar if we could not read the file or if we couldn' unpickle itwe pop up warning message box to inform the user def filequit(selfevent=none)if self okaytocontinue()self parent destroy(this is the last file menu option method we give the user the chance to save any unsaved changesif they cancel we do nothing and the program continuesotherwisewe tell the parent to destroy itself and this leads to clean program termination if we wanted to save user preferences we would do so herejust before the destroy(call def editadd(self*ignore)form addeditform(self parentif form accepted and form nameself data[form nameform url self listbox delete( tkinter endfor name in sorted(self datakey=str lower)self listbox insert(tkinter endnameself dirty true if the user asks to add new bookmark (by clicking edit-addor by clicking the toolbar buttonor by pressing the ctrl+ keyboard shortcut)this method is called the addeditform is custom dialog covered in the next subsectionall that we need to know to use it is that it has an accepted flag which is set to true if the user clicked okand to false if they clicked canceland two data attributesname and urlthat hold the name and url of the bookmark the user has added or edited we create new addeditform which immediately pops up as modal dialog--and therefore blocksso the if form accepted statement is not executed until the dialog has closed if the user clicked ok in the addeditform dialog and they gave the bookmark namewe add the new bookmark' name and url to the self data dictionary
9,116
introduction to gui programming then we clear the list box and reinsert all the data in sorted order it would be more efficient to simply insert the new bookmark in the right placebut even with hundreds of bookmarks the difference would hardly be noticeable on modern machine at the end we set the dirty flag since we now have an unsaved change def editedit(self*ignore)indexes self listbox curselection(if not indexes or len(indexes return index indexes[ name self listbox get(indexform addeditform(self parentnameself data[name]if form accepted and form nameself data[form nameform url if form name !namedel self data[nameself listbox delete( tkinter endfor name in sorted(self datakey=str lower)self listbox insert(tkinter endnameself dirty true editing is slightly more involved than adding because first we must find the bookmark the user wants to edit the curselection(method returns (possibly emptylist of index positions for all its selected items if exactly one item is selected we retrieve its text since that is the name of the bookmark the user wants to edit (and also the key to the self data dictionarywe then create new addeditform passing the name and url of the bookmark the user wants to edit after the form has been closedif the user clicked ok and set nonempty bookmark name we update the self data dictionary if the new name and the old name are the same we can just set the dirty flag and we are finished (in this case presumably the user edited the url)but if the bookmark' name has changed we delete the dictionary item whose key is the old nameclear the list boxand then repopulate the list box with the bookmarks just as we did after adding bookmark def editdelete(self*ignore)indexes self listbox curselection(if not indexes or len(indexes return index indexes[ name self listbox get(indexif tkinter messagebox askyesno("bookmarks delete""delete '{ }'?format(name))
9,117
self listbox delete(indexself listbox focus_set(del self data[nameself dirty true to delete bookmark we must first find out which bookmark the user has chosenso this method begins with the same lines that the mainwindow editedit(method starts with if exactly one bookmark is selected we pop up message box asking the user whether they really want to delete it if they say yes the message box function returns true and we delete the bookmark from the list box and from the self data dictionaryand set the dirty flag we also set the keyboard focus back to the list box def editshowwebpage(self*ignore)indexes self listbox curselection(if not indexes or len(indexes return index indexes[ url self data[self listbox get(index)webbrowser open_new_tab(urlif the user invokes this method we find the bookmark they have selected and retrieve the corresponding url from the self data dictionary then we use the webbrowser module' webbrowser open_new_tab(function to open the user' web browser with the given url if the web browser is not already runningit will be launched application tkinter tk(path os path join(os path dirname(__file__)"images/"if sys platform startswith("win")icon path "bookmark icoapplication iconbitmap(icondefault=iconelseapplication iconbitmap("@path "bookmark xbm"window mainwindow(applicationapplication protocol("wm_delete_window"window filequitapplication mainloop(the last lines of the program are similar to those used for the interest-tk pyw program we saw earlierbut with three differences one difference is that if the user clicks the program window' close box different method is called for the bookmarks program than the one used for the interest program another difference is that on windows the iconbitmap(method has an additional argument which allows us to specify default icon for all the program' windows--this is not needed on unix platforms since this happens automatically and the last difference is that we set the application' title (in the title
9,118
introduction to gui programming barin the mainwindow class' methods rather than here for the interest program the title never changedso it needed to be set only oncebut for the bookmarks program we change the title text to include the name of the bookmarks file being worked on now that we have seen the implementation of the main window' class and the code that initializes the program and starts off the event loopwe can turn our attention to the addeditform dialog creating custom dialog |the addeditform dialog provides means by which users can add and edit bookmark names and urls it is shown in figure where it is being used to edit an existing bookmark (hence the "editin the titlethe same dialog can also be used for adding bookmarks we will begin by reviewing the dialog' initializerbroken into four parts figure the bookmarks program' add/edit dialog class addeditform(tkinter toplevel)def __init__(selfparentname=noneurl=none)super(__init__(parentself parent parent self accepted false self transient(self parentself title("bookmarks "editif name is not none else "add")self namevar tkinter stringvar(if name is not noneself namevar set(nameself urlvar tkinter stringvar(self urlvar set(url if url is not none else "we have chosen to inherit tkinter toplevela bare widget designed to serve as base class for widgets used as top-level windows we keep reference to the parent and create self accepted attribute and set it to false the call to the transient(method is done to inform the parent window that this window must always appear on top of the parent the title is set to indicate adding or editing depending on whether name and url have been passed in two
9,119
tkinter stringvars are created to keep track of the bookmark' name and urland both are initialized with the passed-in values if the dialog is being used for editing namelabel nameentry urllabel urlentry okbutton cancelbutton figure the bookmarks program' add/edit dialog' layout frame tkinter frame(selfnamelabel tkinter label(frametext="name:"underline= nameentry tkinter entry(frametextvariable=self namevarnameentry focus_set(urllabel tkinter label(frametext="url:"underline= urlentry tkinter entry(frametextvariable=self urlvarokbutton tkinter button(frametext="ok"command=self okcancelbutton tkinter button(frametext="cancel"command=self closenamelabel grid(row= column= sticky=tkinter wpady= padx= nameentry grid(row= column= columnspan= sticky=tkinter ewpady= padx= urllabel grid(row= column= sticky=tkinter wpady= padx= urlentry grid(row= column= columnspan= sticky=tkinter ewpady= padx= okbutton grid(row= column= sticky=tkinter ewpady= padx= cancelbutton grid(row= column= sticky=tkinter ewpady= padx= the widgets are created and laid out in gridas illustrated in figure the name and url text entry widgets are associated with the corresponding tkinter stringvars and the two buttons are set to call the self ok(and self close(methods shown further on frame grid(row= column= sticky=tkinter nsewframe columnconfigure( weight= window self winfo_toplevel(window columnconfigure( weight= it only makes sense for the dialog to be resized horizontallyso we make the window frame' second column horizontally resizable by setting its column weight to --this means that if the frame is horizontally stretched the widgets
9,120
introduction to gui programming in column (the name and url text entry widgetswill grow to take advantage of the extra space similarlywe make the window' column horizontally resizable by setting its weight to if the user changes the dialog' heightthe widgets will keep their relative positions and all of them will be centered within the windowbut if the user changes the dialog' widththe name and url text entry widgets will shrink or grow to fit the available horizontal space self bind(""lambda *ignorenameentry focus_set()self bind(""lambda *ignoreurlentry focus_set()self bind(""self okself bind(""self closeself protocol("wm_delete_window"self closeself grab_set(self wait_window(selfwe created two labelsnameand url:which indicate that they have keyboard accelerators alt+ and alt+uwhich when clicked will give the keyboard focus to their corresponding text entry widgets to make this work we have provided the necessary keyboard bindings we use lambda functions rather than pass the focus_set(methods directly so that we can ignore the event argument we have also provided the standard keyboard bindings (enter and escfor the ok and cancel buttons we use the protocol(method to specify the method to call if the user closes the dialog by clicking the close button the calls to grab_set(and wait_window(are both needed to turn the window into modal dialog def ok(selfevent=none)self name self namevar get(self url self urlvar get(self accepted true self close(if the user clicks ok (or presses enter)this method is called the texts from the tkinter stringvars are copied to correponding instance variables (which are only now created)the self accepted variable is set to trueand we call self close(to close the dialog def close(selfevent=none)self parent focus_set(self destroy(this method is called from the self ok(methodor if the user clicks the window' close box or if the user clicks cancel (or presses escit gives the keyboard focus back to the parent and makes the dialog destroy itself in this context destroy just means that the window and its widgets are destroyedthe addeditform instance continues to exist because the caller has reference to it
9,121
after the dialog has been closed the caller checks the accepted variableand if trueretrieves the name and url that were added or edited thenonce the mainwindow editadd(or mainwindow editedit(method has finishedthe addeditform object goes out of scope and is scheduled for garbage collection summary ||this gave you flavor of gui programming using the tk gui library tk' big advantage is that it comes as standard with python but it has many drawbacksnot the least of which is that it is vintage library that works somewhat differently than most of the more modern alternatives if you are new to gui programmingkeep in mind that the major cross-platform competitors to tk--pygtkpyqtand wxpython--are all much easier to learn and use than tkand all can achieve better results using less code furthermorethese tk competitors all have more and better python-specific documentationfar more widgetsand better look and feeland allow us to create widgets from scratch with complete control over their appearance and behavior although tk is useful for creating very small programs or for situations where only python' standard library is availablein all other circumstances any one of the other cross-platform libraries is much better choice exercises ||the first exercise involves copying and modifying the bookmarks program shown in this the second exercise involves creating gui program from scratch copy the bookmarks-tk pyw program and modify it so that it can import and export the dbm files that the bookmarks py console program (created as an exercise in uses provide two new menu options in the file menuimport and export make sure you provide keyboard shortuts for both (keep in mind that ctrl+ is already in use for edit-editsimilarlycreate two corresponding toolbar buttons this involves adding about five lines of code to the main window' initializer two methods to provide the functionality will be requiredfileimport(and fileexport()between them fewer than lines of code including error handling for importing you can decide whether to merge imported bookmarksor to replace the existing bookmarks with those imported the code is not difficultbut does require quite bit of care solution (that merges imported bookmarksis provided in bookmarks-tk_ans py
9,122
introduction to gui programming note that while on unix-like systems file suffix of dbm is fineon windows each dbm "fileis actually three files so for windows file dialogs the pattern should be dbm dat and the default extension dbm dat--but the actual filename should have suffix of dbmso the last four characters must be chopped off the filename in we saw how to create and use regular expressions to match text create dialog-style gui program that can be used to enter and test regexesas shown in figure figure the regex program you will need to read the re module' documentation since the program must behave correctly in the face of invalid regexes or when iterating over the match groupssince in most cases the regex won' have as many match groups as there are labels to show them make sure the program has full support for keyboard users--with navigation to the text entry widgets using alt+ and alt+tcontrol of the checkboxes with alt+ and alt+dprogram termination on ctrl+ and escand recalculation if the user presses and releases key in either of the text entry widgetsand whenever checkbox is checked or unchecked the program is not too difficult to writealthough the code for displaying the matches and the group numbers (and names where specifiedis tiny bit tricky-- solution is provided in regex-tk pywwhich is about one hundred forty lines
9,123
epilogue if you've read at least the first six and either done the exercises or written your own python programs independentlyyou should be in good position to build up your experience and programming skills as far as you want to go--python won' hold you backto improve and deepen your python language skillsif you read only the first six make sure you are familiar with the material in and that you read and experiment with at least some of the material in and in particular the with statement and context managers it is also worth reading at least ' section on testing keep in mindthoughthat apart from the pleasure and learning aspects of developing everything from scratchdoing so is rarely necessary in python we have already mentioned the standard library and the python package indexpypi python org/pypiboth of which provide huge amount of functionality in additionthe online python cookbook at code activestate comrecipes/langs/pythonoffers large number of trickstipsand ideasalthough it is python -oriented at the time of this writing it is also possible to create modules for python in other languages (any language that can export functionsas most canthese can be developed to work cooperatively with python using python' api shared libraries (dlls on windows)whether created by us or obtained from third partycan be accessed from python using the ctypes modulegiving us virtually unlimited access to the vast amount of functionality available over the internet thanks to the skill and generosity of open source programmers worldwide and if you want to participate in the python communitya good place to start is www python org/community where you will find wikis and many general and special-interest mailing lists
9,124
|||this is small selected annotated bibliography of programming-related books most of the books listed are not python-specificbut all of them are interestinguseful--and accessible clean code robert martin (prentice hall isbn this book addresses many "tacticalissues in programminggood namingfunction designrefactoringand similar the book has many interesting and useful ideas that should help any programmer improve their coding style and make their programs more maintainable (the book' examples are in java code completea practical handbook of software constructionsecond edition steve mcconnell (microsoft press isbn this book shows how to build solid softwaregoing beyond the language specifics into the realms of ideasprinciplesand practices the book is packed with ideas that will make any programmer think more deeply about their programming (the book' examples are mostly in ++javaand visual basic domain-driven design eric evans (addison-wesley isbn very interesting book on software designparticularly useful for largemultiperson projects at its heart it is about creating and refining domain models that represent what the system is designed to doand about creating ubiquitous language through which all those involved with the system--not just software engineers--can communicate their ideas (the book' examples are in java design patterns erich gammarichard helmralph johnsonjohn vlissides (addisonwesley isbn deservedly one of the most influential programming books of modern times the design patterns are fascinating and of great practical use in everyday programming (the book' examples are in +mastering regular expressionsthird edition jeffrey friedl ( 'reilly isbn this is the standard text on regular expressions-- very interesting and useful book most of the coverage is understandably devoted to
9,125
selected bibliography perl--which probably has more regular expression features than any other tool howeversince python supports large subset of what perl provides (plus python' own ? extensions)the book is still useful to python programmers parsing techniquesa practical guidesecond edition dick gruneceriel jacobs (springer isbn xthis book provides comprehensive and in-depth coverage of parsing the first edition can be downloaded in pdf format from www cs vu nl/~dickptapg html python cookbooksecond edition alex martellianna ravenscroftdavid ascher ( 'reilly isbn this book is full of interesting--and practical--ideas covering all aspects of python programming the second edition is based on python so it might be worthwhile waiting and hoping for python -specific edition to appear python essential referencefourth edition david beazley (addison-wesley isbn the book' title is an accurate description the fourth edition has been updated to cover both python and python there is little overlap with this bookbut most of the essential reference is devoted to python' standard library as well as covering more advanced features such as extending python with libraries and embedding the python interpreter into other programs rapid gui programming with python and qt mark summerfield (prentice hall isbn this book (by this book' authorteaches pyqt programing pyqt (built on top of nokia' ++/qt gui toolkitis probably the easiest-to-use crossplatform gui libraryand the one that arguably produces the best user interfaces--especially compared with tkinter the book uses python although python versions of the examples are available from the book' web site
9,126
all functions and methods are listed under their class or moduleand in most cases also as top-level terms in their own right for modules that contain classeslook under the class for its methods where method or function name is close enough to conceptthe concept is not usually listed for examplethere is no entry for "splitting strings"but there are entries for the str split(method symbols (addition operatorconcatenation !(not equal operator) +(addition augmented assignment operator) operatorappend/extend operator) (subtraction operatornegation operator) -(subtraction augmented assignment operator) (division operator) /(division augmented assignment operator) /(truncating division operator) //(truncating division augmented assignment operator) (less than operator) <(int shift left operator) <<(int shift left augmented assignment operator) <(less than or equal to operator) (name binding operatorobject reference creation and assignment operator) =(equal to operator) (greater than operator) >(greater than or equal to operator) >(int shift right operator) comment character (modulus/remainder operator) %(modulus augmented assignment operator) (bitwise and operator) &(bitwise and augmented assignment operator) ((tuple creation operatorfunction and method call operatorexpression operator) (multiplication operatorreplication operatorsequence unpackerfrom import operator) - *(multiplication augmented assignment operatorreplication augmented assignment operator) *(power/exponentiation operatormapping unpacker) **(power/exponentiation augmented assignment operator)
9,127
index >>(int shift right augmented asadd((set type) signment operator) (decorator operator) - [(indexing operatoritem access operatorslicing operator) \ (newline characterstatement terminator) (bitwise xor operator) ^(bitwise xor augmented assignment operator) (underscore) (bitwise or operator) |(bitwise or augmented assignment operator) (bitwise not operator) aggregating data aggregation aifc module algorithmfor searching algorithmfor sorting algorithmmd __all__ (attribute) all((built-in) alternationregex - __and__((&) and (logical operator) annotations - __annotations__ (attribute) anonymous functionssee lambda statement any((built-in) abc module abcmeta type @abstractmethod() abstractproperty() __abs__() abs((built-in) abspath((os path module) abstract base class (abc) - see also collections and numbers modules abstract py (example) abstract syntax tree (ast) @abstractmethod((abc module) abstractproperty((abc module) acceleratorkeyboard access control acos((math module) acosh((math module) __add__((+) append(bytearray type list type archive files argumentscommand-line argumentsfunction default immutable keyword - mutable positional - unpacking - argumentsinterpreter argv list (sys module) array module arraysize attribute (cursor object) as_integer_ratio((float type) as (binding operator) ascii((built-in) ascii encoding - see also character encodings asin((math module) asinh((math module)
9,128
askopenfilename((tkinter filedialog module) asksaveasfilename((tkinter filedialog module) askyesno((tkinter messagebox module) askyesnocancel((tkinter messagebox module) assert (statement) - assertionerror (exception) assertionsregex - associativity - ast (abstract syntax tree) asynchat module asyncore module atan((math module) atan ((math module) atanh((math module) attrgetter((operator module) attribute __all__ __annotations__ __call__ __class__ __dict__ __doc__ __file__ __module__ __name__ private __slots__ attribute access methodstable of attributeerror (exception) attributes - - attributesmutable and immutable audio-related modules audioop module augmented assignment - - optioninterpreter backreferencesregex backtracesee traceback backups base module - basename((os path module) berkeley db bigdigits py (example) - bikestock py (example) - bin((built-in) binary data binary files - - binary numbers binary search see also bisect module binaryrecordfile py (example) - bindingsevent bindingskeyboard bisect module bit_length((int type) bitwise operatorstable of block structureusing indentation blocks py (example) - - - bnf (backus-naur form) - bookmarks-tk pyw (example) - __bool__() bool((built-in) bool type bool((built-in) conversion boolean expressions branchingsee if statement branchingwith dictionaries - break (statement)
9,129
index built-in abs() all() any() ascii() bin() bool() chr() @classmethod() compile() complex() delattr() dict() dir() divmod() enumerate() - eval() exec() - filter() float() format() frozenset() getattr() globals() hasattr() hash() help() hex() id() __import__() input() int() isinstance() issubclass() iter() len() list() locals() map() max() built-in (cont min() next() oct() ord() pow() print() @property() - range() - repr() reversed() round() set() setattr() sorted() - @staticmethod() str() sum() super() tuple() type() vars() zip() - builtins module button type (tkinter module) byte-code byte order bytearray type - append() capitalize() center() count() decode() endswith() expandtabs() extend() find()
9,130
bytearray type (cont fromhex() index() insert() isalnum() isalpha() isdigit() islower() isspace() istitle() isupper() join() ljust() lower() lstrip() methodstable of partition() pop() remove() replace() reverse() rfind() rindex() rjust() rpartition() rsplit() rstrip() split() splitlines() startswith() strip() swapcase() title() translate() upper() zfill() bytes type - capitalize() center() count() decode() endswith() expandtabs() bytes type (cont find() fromhex() index() isalnum() isalpha() isdigit() islower() isspace() istitle() isupper() join() literal ljust() lower() lstrip() methodstable of partition() replace() rfind() rindex() rjust() rpartition() rsplit() rstrip() split() splitlines() startswith() strip() swapcase() title() translate() upper() zfill() bz (extension) bz module - optioninterpreter calcsize((struct module) calendar module __call__ (attribute) __call__()
9,131
index call((subprocess module) callablesee functions and methods callable abc (collections module) callable objects @classmethod() clear(dict type set type close(capitalize(bytearray type bytes type str type connection object coroutines cursor object file object closed attribute (file object) closures cmath module code comments collation order (unicode) - collectionssee dictlistsetand tuple types collectionscopying - collections module - callable abc classestable of container abc defaultdict type - deque type hashable abc iterable abc iterator abc mapping abc mutablemapping abc mutablesequence abc mutableset abc namedtuple type - ordereddict type - sequence abc set abc sized abc combining functions - - command-line argumentssee sys argv list comment character (#) commit((connection object) comparing files and directories capturesregex - car_registration_server py (example) - car_registration py (example) - case statementsee dictionary branching category((unicodedata module) ceil((math module) center(bytearray type bytes type str type cgi module cgitb module chaining exceptions - changing dictionaries changing lists character classregex character encodings - see also ascii encodinglatin encodingunicode chargrid py (example) - chdir((os module) checktags py (example) choice((random module) chr((built-in) class (statement) __class__ (attribute) classmixin class decorators - - class methods class variables classesimmutable
9,132
comparing objects comparing strings - comparisonssee and >operators compile(built-in re module __complex__() complex((built-in) complex abc (numbers module) complex type - complex((built-in) conjugate() imag attribute real attribute composing functions - - composition comprehensionssee under dictlistand set types compressing files concatenation of lists of strings of tuples conceptsobject-oriented conditional branchingsee if statement conditional expression configparser module configuration files conjugate((complex type) connect((sqlite module) connection object close() commit() cursor() methodstable of rollback() see also cursor object constant setsee frozenset type constants - container abc (collections module) __contains__() context managers - contextlib module continue (statement) conversions date and time float to int int to character int to float to bool to complex to dict to float to int to list to set to str to tuple convert-incidents py (example) - coordinated universal time (utc) __copy__() copy(copy module dict type frozenset type set type copy module copy() deepcopy() copying collections - copying objects copysign((math module) coroutines - close() decorator send() cos((math module) cosh((math module) count(bytearray type
9,133
count((cont bytes type list type str type tuple type cprofile module - create table (sql statement) creationof objects csv (extension) csv module csv html py (example) - csv html _opt py (example) ctypes module curryingsee partial function application cursor((connection object) cursor object arraysize attribute close() description attribute execute() executemany() fetchall() fetchmany() fetchone() methodstable of rowcount attribute see also connection object custom exceptions - custom functionssee functions custom modules and packages - daemon threads data persistence data structuressee dictlistsetand tuple types data type conversionsee conversions index database connectionsee connection object database cursorsee cursor object datetime date type (datetime module) fromordinal() today() toordinal() datetime datetime type (datetime modulenow() strptime() utcnow() datetime module date type datetime type db-apisee connection object and cursor object deadlock __debug__ constant debug (normalmodesee pythonoptimize debuggerssee idle and pdb module decimal module - decimal() decimal type - decode(bytearray type bytes type decoratesortundecorate (dsu) decorating methods and functions - decorator class - - @classmethod() @functools wraps() @property() - @staticmethod() dedent((textwrap module)
9,134
deep copyingsee copying collections deepcopy((copy module) def (statement) - default arguments defaultdict type (collections module) - degrees((math module) del (statement) __del__() __delattr__() delattr((built-in) delegation delete (sql statement) __delitem__(([]) deque type (collections module) description attribute (cursor object) descriptors - - detach((stdin file object) development environment (idle) - - dialogsmodal __dict__ (attribute) dict type - changing clear() comparing comprehensions - copy() dict((built-in) fromkeys() get() inverting items() keys() methodstable of pop() popitem() setdefault() dict type (cont update() updating values() view see also collections defaultdictcollections ordereddictand sorteddict py dictionaryinverting dictionary branching - dictionary comprehensions - dictionary keys difference_update((set type) difference(frozenset type set type difflib module digit_names py (example) __dir__() dir((built-in) directoriescomparing directoriestemporary directory handling - dirname((os path module) discard((set type) __divmod__() divmod((built-in) __doc__ (attribute) docstrings - see also doctest module doctest module - - documentation dom (document object model)see xml dom module domain-specific language (dsl) doublevar type (tkinter module) dsl (domain-specific language) dsu (decoratesortundecorate)
9,135
duck typingsee dynamic typing dump((pickle module) dumps((pickle module) duplicateseliminating dvds-dbm py (example) - dvds-sql py (example) - dynamic code execution - dynamic functions dynamic imports - dynamic typing index environment variable lang path pythondontwritebytecode pythonoptimize pythonpath environmenterror (exception) eoferror (exception) epsilonsee sys float_info epsilon attribute __eq__((==) (constant(math module) editor (idle) - - element treessee xml etree package elif (statement)see if statement else (statement)see for loopif statementand while loop email module encode((str type) encoding attribute (file object) encoding errors encodings - encodingsxml end((match object) end constant (tkinter module) endianness endpos attribute (match object) endswith(bytearray type bytes type str type __enter__() entitieshtml entry type (tkinter module) enumerate((built-in) - enumssee namedtuple type environ mapping (os module) error handlingsee exception handling error-handling policy escape(re module xml sax saxutils module escapeshtml and xml escapesstring escapingnewlines eval((built-in) event bindings event loop example abstract py bigdigits py - bikestock py - binaryrecordfile py - blocks py - - - bookmarks-tk pyw - car_registration_server py - car_registration py - chargrid py - checktags py convert-incidents py - csv html py - csv html _opt py digit_names py dvds-dbm py -
9,136
example (cont dvds-sql py - external_sites py externalstorage py finddup py findduplicates- py - first-order-logic py - - fuzzybool py - fuzzyboolalt py - generate_grid py - generate_test_names py generate_test_names py generate_usernames py - grepword- py grepword- py - grepword py grepword- py - html text py image py - indentedlist py - interest-tk pyw - magic-numbers py - make_html_skeleton py - noblanks py playlists py - - - print_unicode py - property py quadratic py - shape py - shapealt py - sorteddict py - sortedlist py - sortkey py statistics py - textfilter py textutil py - uniquewords py uniquewords py untar py valid py - xmlshadow py except (statement)see try statement exception assertionerror attributeerror custom - environmenterror eoferror exception importerror indexerror ioerror keyboardinterrupt keyerror lookuperror nameerror notimplementederror oserror stopiteration syntaxerror - typeerror unicodedecodeerror unicodeencodeerror valueerror zerodivisionerror exception (exception) exception handling - see also try statement exceptionschaining - exceptionscustom - exceptionspropagating exec((built-in) - executable attribute (sys module) execute((cursor object) executemany((cursor object) exists((os path module) __exit__() exit((sys module) exp((math module)
9,137
index expand((match object) expandtabs(bytearray type bytes type str type expat xml parser expressionconditional expressionsboolean extend(bytearray type list type extending lists extension bz csv gz ini pls py pyc and pyo pyw svg tartar gztar bz tgz wav xpm zip external_sites py (example) externalstorage py (example) fabs((math module) factorial((math module) factory functions false (built-in constant)see bool type fetchall((cursor object) fetchmany((cursor object) fetchone((cursor object) __file__ (attribute) file associationswindows file extensionsee extension file globbing file handling - file object close() closed attribute encoding attribute fileno() flush() isatty() methodstable of mode attribute name attribute newlines attribute __next__() open() peek() read() readable() readinto() readline() readlines() seek() seekable() stderr (sys module) stdin (sys module) stdin detach() stdout (sys module) tell() truncate() writable() write() writelines() file suffixsee extension file system interaction - file transfer protocol (ftp) filecmp module fileinput module fileno((file object) filessee file object and open(filesarchive filesbinary - -
9,138
filescomparing filescompressing and uncompressing filesformat comparison - filesrandom accesssee binary files filestemporary filestext - filesxml - filter((built-in) filtering - finally (statement)see try statement find(bytearray type bytes type str type - findall(re module regex object finddup py (example) findduplicates- py (example) - finditer(re module regex object first-order-logic py (example) - - flags attribute (regex object) __float__() float_info epsilon attribute (sys module) float((built-in) float type - as_integer_ratio() float((built-in) fromhex() hex() is_integer() floor((math module) __floordiv__((//) flush((file object) fmod((math module) focuskeyboard for loop - foreign functions __format__() format(built-in str type - format specificationsfor strings - formatting stringssee str format(fraction type (fractions module) frame type (tkinter module) frexp((math module) from (statement)see chaining exceptions and import statement fromhex(bytearray type bytes type float type fromkeys((dict type) fromordinal((datetime date type) frozenset type - copy() difference() frozenset((built-in) intersection() isdisjoint() issubset() issuperset() methodstable of symmetric_difference() fsum((math module) ftp (file transfer protocol) ftplib module functions - annotations - anonymoussee lambda statement composing - - decorating - - dynamic factory foreign
9,139
functions (cont lambdasee lambda statement local - module object reference to parameterssee argumentsfunction recursive - see also functors functionsintrospection-relatedtable of functionsiteratortable of functionsnestedsee local functions functionstable of (math module) functionstable of (re module) functools module partial() reduce() @wraps() functors - fuzzybool py (example) - fuzzyboolalt py (example) - garbage collection __ge__((>=) generate_grid py (example) - generate_test_names py (example) generate_test_names py (example) generate_usernames py (example) - generator object send() generators - __get__() get((dict type) index __getattr__() getattr((built-in) __getattribute__() getcwd((os module) __getitem__(([]) getmtime((os path module) getopt modulesee optparse module getrecursionlimit((sys module) getsize((os path module) gettempdir((tempfile module) gil (global interpreter lock) glob module global (statement) global functionssee functions global interpreter lock (gil) global variables globals((built-in) globbing gmtsee coordinated universal time grammar greedy regexes grepword- py (example) grepword- py (example) - grepword py (example) grepword- py (example) - grid layout group((match object) groupdict((match object) groupindex attribute (regex object) groups((match object) groupsregex - __gt__((>) gz (extension) gzip module open() write()
9,140
hasattr((built-in) __hash__() hash((built-in) hashable abc (collections module) hashable objects heapq module - help((built-in) hex(built-in float type hexadecimal numbers html entities module html escapes html parser module html text py (example) http package hypot((math module) __iadd__((+=) __iand__((&=) id((built-in) identifiers - identity testingsee is identity operator idle (programming environment) - - if (statement) - __ifloordiv__((//=) __ilshift__((<<=) image py (example) - imap (internet message access protocol) imaplib module immutable arguments immutable attributes immutable classes immutable objects __imod__((%=) import (statement) - __import__((built-in) import order policy importerror (exception) importsdynamic - importsrelative __imul__((*=) in (membership operator) indentationfor block structure indentedlist py (example) - __index__() index(bytearray type bytes type list type str type - tuple type indexerror (exception) indexing operator ([]) infinite loop inheritance - inheritancemultiple - ini (extension) __init__() type type __init__ py package file initializationof objects input((built-in) insert (sql statement) insert(bytearray type list type inspect module installing python - instance variables __int__() int((built-in) int type - bit_length() bitwise operatorstable of conversionstable of
9,141
index int type (cont int((built-in) integral abc (numbers module) interest-tk pyw (example) - internationalization internet message access protocol (imap ) interpreter options intersection_update((set type) intersection(frozenset type set type introspection intvar type (tkinter module) __invert__((~) invertinga dictionary io module stringio type - see also file object and open(ioerror (exception) __ior__((|=) ip address __ipow__((**=) __irshift__((>>=) is_integer((float type) is (identity operator) isalnum(bytearray type bytes type str type isalpha(bytearray type bytes type str type isatty((file object) isdecimal((str type) isdigit(bytearray type bytes type str type isdir((os path module) isdisjoint(frozenset type isdisjoint((cont set type isfile((os path module) isidentifier((str type) isinf((math module) isinstance((built-in) islower(bytearray type bytes type str type isnan((math module) isnumeric((str type) isprintable((str type) isspace(bytearray type bytes type str type issubclass((built-in) issubset(frozenset type set type issuperset(frozenset type set type istitle(bytearray type bytes type str type __isub__((-=) isupper(bytearray type bytes type str type item access operator ([]) itemgetter((operator module) items((dict type) __iter__() iter((built-in) iterablesee iterators iterable abc (collections module)
9,142
iterator abc (collections module) iterators - functions and operatorstable of itertools module __ixor__((^=) join(bytearray type bytes type os path module str type json module key bindings keyboard accelerators keyboard focus keyboard shortcuts keyboardinterrupt (exception) keyerror (exception) keys((dict type) keyword arguments - keywordstable of label type (tkinter module) lambda (statement) - lang (environment variable) lastgroup attribute (match object) lastindex attribute (match object) latin encoding layouts lazy evaluation ldexp((math module) __le__((<=) __len__() len((built-in) lexical analysis librarystandard - lifoqueue type (queue module) linear search list comprehensions - list type - append() changing comparing comprehensions - count() extend() index() insert() list((built-in) methodstable of pop() remove() replication (**=) reverse() slicing - sort() updating see also sortedlist py listbox type (tkinter module) listdir((os module) ljust(bytearray type bytes type str type load((pickle module) loads((pickle module) local functions - local variables
9,143
index locale module setlocale() localization locals((built-in) localtime((time module) lock type (threading module) log((math module) log ((math module) log ((math module) logging module logicshort-circuit logical operatorssee andorand not lookuperror (exception) loopingsee for loop and while loop lower(bytearray type bytes type str type __lshift__((<<) lstrip(bytearray type bytes type str type __lt__((<) (extension) magic number magic-numbers py (example) - mailbox module make_html_skeleton py (example) - makedirs((os module) maketrans((str type) - mandatory parameters map((built-in) mapping mapping abc (collections module) mapping typessee dict and collections defaultdict mapping unpacking (**) match(re module regex object match object end() endpos attribute expand() group() groupdict() groups() lastgroup attribute lastindex attribute methodstable of pos attribute re attribute span() start() string attribute see also re module and regex object math module acos() acosh() asin() asinh() atan() atan () atanh() ceil() copysign() cos() cosh() degrees() (constant) exp() fabs() factorial() floor()
9,144
math module (cont fmod() frexp() fsum() functionstable of hypot() isinf() isnan() ldexp() log() log () log () modf() pi (constant) pow() radians() sin() sinh() sqrt() tan() tanh() trunc() max((built-in) maxunicode attribute (sys module) md (message digest algorithm) membership testingsee in operator memoizing memory managementsee garbage collection menu type (tkinter module) message digest algorithm (md ) metaclasses - methods attribute accesstable of bytearray typetable of bytes typetable of class methods (cont connection objecttable of cursor objecttable of decorating - - dict typetable of file objecttable of frozenset typetable of list typetable of match objecttable of object reference to regex objecttable of set typetable of static str typetable of unimplementing - see also special method mimetypes module min((built-in) minimal regexes missing dictionary keys mixin class mkdir((os module) __mod__((%) modal dialogs mode attribute (file object) modf((math module) __module__ (attribute) module functions modules - modules attribute (sys module) __mul__((*) multiple inheritance - multiprocessing module mutable arguments mutable attributespolicy mutable objectssee immutable objects mutablemapping abc (collections module) mutablesequence abc (collections module) mutableset abc (collections module)
9,145
index number abc (numbers module) numbers module __name__ (attribute) classestable of complex abc integral abc number abc rational abc real abc numeric operators and functionstable of name((unicodedata module) name attribute (file object) name conflictsavoiding name mangling namedtuple type (collections module) - nameerror (exception) namesqualified namespace naming policy - __ne__((!=) __neg__((-) nested collectionssee dictlistsetand tuple types nested functionssee local functions network news transfer protocol (nntp) __new__() object type type type newline escaping newlines attribute (file object) __next__() next((built-in) nntp (network news transfer protocol) nntplib module noblanks py (example) none object nongreedy regexes nonlocal (statement) nonterminal normal (debugmodesee pythonoptimize normalize((unicodedata module) not (logical operator) notimplemented object notimplementederror (exception) now((datetime datetime type) - optioninterpreter object creation and initialization object-oriented concepts and terminology object references - object type __new__() __repr__() objectscomparing obtaining python - oct((built-in) octal numbers open(file object gzip module shelve module operator module attrgetter() itemgetter() operatorsiteratortable of optimized modesee pythonoptimize optional parameters optionsfor interpreter optparse module __or__((|)
9,146
or (logical operator) ord((built-in) ordered collectionssee list and tuple types ordereddict type (collections module) - os module - chdir() environ mapping getcwd() listdir() makedirs() mkdir() remove() removedirs() rename() rmdir() sep attribute stat() system() walk() os path module - abspath() basename() dirname() exists() getmtime() getsize() isdir() isfile() join() split() splitext() oserror (exception) pack((struct module) package directories packages - packrat parsing parameterssee argumentsfunction parametersunpacking - parent-child relationships parsing command-line arguments dates and times text files - with ply - with pyparsing - with regexes - - xml (with dom) - xml (with sax) - xml (with xml etree) - partial((functools module) partial function application - partition(bytearray type bytes type str type pass (statement) path (environment variable) path attribute (sys module) pathsunix-style pattern attribute (regex object) pdb module - peek((file object) pep (python database api specification ) pep (function annotations) pep (introducing abstract base classes) pep (supporting non-ascii identifiers) pep (exception chaining and embedded tracebacks) persistenceof data photoimage type (tkinter module) pi (constant(math module) pickle module - dump() dumps() load()
9,147
pickle module (cont loads() pickles - pipelines - pipessee subprocess module placeholderssql platform attribute (sys module) playlists py (example) - - - pls (extension) ply p_error() precedence variable states variable - t_error() t_ignore variable t_newline() tokens variable pointerssee object references policyerror handling policyimport order policymutable attributes policynaming - polymorphism - pop(bytearray type dict type list type set type pop (post office protocol) popen((subprocess module) popitem((dict type) poplib module __pos__((+) pos attribute (match object) positional arguments - post office protocol (pop ) __pow__((**) pow(built-in math module pprint module precedence - index print_unicode py (example) - print((built-in) priorityqueue type (queue module) private attributes processing pipelines - processor endianness profile module - propagating exceptions properties - @property() - property py (example) py (extension) pyc and pyo (extension) pygtk pyparsing (concatenation operator) (concatenation operator) <(append operator) (or operator) alphanums alphas caselessliteral() charsnotin() combine() delimitedlist() empty() forward() group() keyword() lineend() literal() makehtmltags() nums oneormore() operatorprecedence() - optional() pythonstylecomment quotedstring
9,148
pyparsing (cont regex() restofline skipto() suppress() word() zeroormore() pyqt pythondontwritebytecode (environment variable) python enhancement proposalssee peps python shell (idle or interpreter) pythonoptimize (environment variable) pythonpath (environment variable) pyw (extension) quadratic py (example) - qualified names quantifiersregex - queue module lifoqueue type priorityqueue type queue type queue type (queue module) quopri module quoteattr((xml sax saxutils module) __radd__((+) radians((math module) raise (statement) see also try statement __rand__((&) random access filessee binary files random module choice() sample() range((built-in) - rational abc (numbers module) raw binary datasee binary files raw strings __rdivmod__() re attribute (match object) re module - compile() escape() findall() finditer() functionstable of match() search() split() sub() subn() see also match object and regex object read((file object) readable((file object) readinto((file object) readline((file object) readlines((file object) real abc (numbers module) recordssee struct module recursive descent parser recursive functions - recv((socket module) reduce((functools module) reducing referencessee object references regex alternation - assertions - backreferences captures - character classes
9,149
regex (cont flags greedy groups - matchsee match object nongreedy quantifiers - special characters regex object findall() finditer() flags attribute groupindex attribute match() methodstable of pattern attribute search() split() sub() subn() see also re module and match object relational integrity relative imports remove(bytearray type list type os module set type removedirs((os module) rename((os module) replace(bytearray type bytes type str type replication (**=of lists of strings of tuples __repr__() object type repr((built-in) representational form - resizable windows - index return (statement) reverse(bytearray type list type __reversed__() reversed((built-in) reversing strings rfind(bytearray type bytes type str type __rfloordiv__((//) rindex(bytearray type bytes type str type rjust(bytearray type bytes type str type __rlshift__((<<) rmdir((os module) __rmod__((%) __rmul__((*) rollback((connection object) __ror__((|) __round__() round((built-in) rowcount attribute (cursor object) rpartition(bytearray type bytes type str type __rpow__((**) __rrshift__((>>) __rshift__((>>) rsplit(bytearray type bytes type str type rstrip(bytearray type
9,150
rstrip((cont bytes type str type __rsub__((-) __rtruediv__((/) run((thread type) __rxor__((^) sample((random module) sax (simple api for xml)see xml sax module scalable vector graphics (svg) scale type (tkinter module) scanning scrollbar type (tkinter module) search(re module regex object searching seek((file object) seekable((file object) select (sql statement) self object send(coroutines generator object socket module sendall((socket module) sep attribute (os module) sequence abc (collections module) sequence typessee bytearraybytesliststrand tuple types sequence unpacking (*) - serialized data accessfor threads serializingsee pickles __set__() set abc (collections module) set comprehensions set type - add() clear() comprehensions copy() difference_update() difference() discard() intersection_update() intersection() isdisjoint() issubset() issuperset() methodstable of pop() remove() set((built-in) symmetric_difference_update() symmetric_difference() union() update() set typessee frozenset and set types __setattr__() setattr((built-in) setdefault((dict type) __setitem__(([]) setlocale((locale module) setrecursionlimit((sys module) shallow copyingsee copying collections shape py (example) - shapealt py (example) - shebang (shell execute) shellpython (idle or interpreter) shell execute (#!)
9,151
index shelve module open() sync() sortkey py (example) short-circuit logic shortcutkeyboard showwarning((tkinter messagebox module) shutil module simple api for xml (sax)see xml sax module simple mail transfer protocol (smtp) sin((math module) single shot timer sinh((math module) site-packages directory sized abc (collections module) slicing ([]bytes lists - operator strings - tuples __slots__ (attribute) smtp (simple mail transfer protocol) smtpd module smtplib module sndhdr module socket module recv() send() sendall() socket() socketserver module sort((list type) sort algorithm sorted((built-in) - sorteddict py (example) - sortedlist py (example) - special charactersregex special method __abs__() __add__((+) __and__((&) bitwise and numeric methodstable of __bool__() __call__() collection methodstable of comparison methodstable of __complex__() __contains__() __copy__() __del__() __delattr__() __delitem__(([]) __dir__() __divmod__() __enter__() __eq__((==) __exit__() __float__() __floordiv__((//) __format__() fundamental methodstable of __ge__((>=) __get__() __getattr__() __getattribute__() __getitem__(([]) __gt__((>) __hash__() __iadd__((+=) __iand__((&=) __ifloordiv__((//=) __ilshift__((<<=) sound-related modules span((match object)
9,152
special method (cont __imod__((%=) __imul__((*=) __index__() __init__() __int__() __invert__((~) __ior__((|=) __ipow__((**=) __irshift__((>>=) __isub__((-=) __iter__() __ixor__((^=) __le__((<=) __len__() __lshift__((<<) __lt__((<) __mod__((%) __mul__((*) __ne__((!=) __neg__((-) __new__() __next__() __or__((|) __pos__((+) __pow__((**) __radd__((+) __rand__((&) __rdivmod__() __repr__() __reversed__() __rfloordiv__((//) __rlshift__((<<) __rmod__((%) __rmul__((*) __ror__((|) __round__() __rpow__((**) __rrshift__((>>) __rshift__((>>) __rsub__((-) __rtruediv__((/) __rxor__((^) special method (cont __set__() __setattr__() __setitem__(([]) __str__() __sub__((-) __truediv__((/) __xor__((^) split(bytearray type bytes type os path module re module regex object str type splitext((os path module) splitlines(bytearray type bytes type str type sql databases sql placeholders sql statement create table delete insert select update sqlite module connect() sqrt((math module) ssl module standard library - starred arguments starred expressionssee sequence unpacking start(match object thread type start symbol startswith(bytearray type bytes type
9,153
contents tic-tac-toe example further topics exercises ii graphics gui programming with tkinter basics labels grid entry boxes buttons global variables tic-tac-toe gui programming ii frames colors images canvases check buttons and radio buttons text widget scale widget gui events event examples gui programming iii title bar disabling things getting the state of widget message boxes destroying things updating dialogs menu bars new windows pack stringvar more with guis further graphical programming python vs python the python imaging library pygame
9,154
vii iii intermediate topics miscellaneous topics iii mutability and references tuples sets unicode sorted if-else operator continue eval and exec enumerate and zip copy more with strings miscellaneous tips and tricks running your python programs on other computers useful modules importing modules dates and times working with files and directories running and quitting programs zip files getting files from the internet sound your own modules regular expressions introduction syntax summary groups other functions examples math the math module scientific notation comparing floating point numbers fractions the decimal module complex numbers more with lists and arrays random numbers miscellaneous topics
9,155
contents using the python shell as calculator working with functions first-class functions anonymous functions recursion mapfilterreduceand list comprehensions the operator module more about function arguments the itertools and collections modules permutations and combinations cartesian product grouping things miscellaneous things from itertools counting things defaultdict exceptions basics try/except/else try/finally and with/as more with exceptions bibliography index
9,156
my goal here is for something that is partly tutorial and partly reference book like how tutorials get you up and running quicklybut they can often be little wordy and disorganized reference books contain lot of good informationbut they are often too terseand they don' often give you sense of what is important my aim here is for something in the spirit of tutorial but still useful as reference summarize information in tables and give lot of short example programs also like to jump right into things and fill in background information as gorather than covering the background material first this book started out as about pages of notes for students in my introductory programming class at mount st mary' university most of these students have no prior programming experienceand that has affected my approach leave out lot of technical details and sometimes oversimplify things some of these details are filled in later in the bookthough other details are never filled in but this book is not designed to cover everythingand recommend reading other books and the python documentation to fill in the gaps the style of programming in this book is geared towards the kinds of programming things like to do--short programsoften of mathematical naturesmall utilities to make my life easierand small computer games in factthe things cover in the book are the things that have found most useful or interesting in my programming experienceand this book serves partly to document those things for myself this book is not designed as thorough preparation for career in software engineering interested readers should progress from this book to book that has more on computer science and the design and organization of large programs in terms of structuring course around this book or learning on your ownthe basis is most of part the first four are critically important is usefulbut not all of it is critical (stringsshould be done before (lists contains some more advanced list topics much of this can be skippedthough it is all interesting and useful in particularthat covers list comprehensionswhich use extensively later in the book while you can get away without using list comprehensionsthey provide an elegant and efficient way of doing things (while loopsis important contains bunch of miscellaneous topicsall of which are usefulbut many can be skipped if need be the final four of part are about dictionariestext filesfunctionsand object-oriented programming part ii is about graphicsmostly gui programming with tkinter you can very quickly write some nice programs using tkinter for instancesection presents -line working (though not ix
9,157
contents perfecttic-tac-toe game the final of part ii covers bit about the python imaging library part iii contains lot of the fun and interesting things you can do with python if you are structuring one-semester course around this bookyou might want to pick few topics in part iii to go over this part of the book could also serve as reference or as place for interested and motivated students to learn more all of the topics in this part of the book are things that have found useful at one point or another though this book was designed to be used in an introductory programming courseit is also useful for those with prior programming experience looking to learn python if you are one of those peopleyou should be able to breeze through the first several you should find part ii to be concisebut not superficialtreatment on gui programming part iii contains information on the features of python that allow you to accomplish big things with surprisingly little code in preparing this book the python documentation at www python org was indispensable this book was composed entirely in latex there are number of latexpackagesparticularly listings and hyperrefthat were particulary helpful latexcode from me get the listings package to nicely highlight the python code listings for the longer programs are available at files used in the text and exercises are available at don' have solutions available to the exercises herebut there is separate set of few hundred exercises and solutions at please send commentscorrectionsand suggestions to heinold@msmary edu last updated march
9,158
getting started this will get you up and running with pythonfrom downloading it to writing simple programs installing python go to www python org and download the latest version of python (version as of this writingit should be painless to install if you have mac or linuxyou may already have python on your computerthough it may be an older version if it is version or earlierthen you should install the latest versionas many of the programs in this book will not work correctly on older versions idle idle is simple integrated development environment (idethat comes with python it' program that allows you to type in your programs and run them there are other ides for pythonbut for now would suggest sticking with idle as it is simple to use you can find idle in the python folder on your computer when you first start idleit starts up in the shellwhich is an interactive window where you can type in python code and see the output in the same window often use the shell in place of my calculator or to try out small pieces of code but most of the time you will want to open up new window and type the program in there note at least on windowsif you click on python file on your desktopyour system will run the programbut not show the codewhich is probably not what you want insteadif you right-click on the filethere should be an option called edit with idle to edit an existing python file
9,159
getting started either do that or start up idle and open the file through the file menu keyboard shortcuts the following keystrokes work in idle and can really speed up your work keystroke result ctrl+ copy selected text ctrl+ cut selected text ctrl+ paste ctrl+ undo the last keystroke or group of keystrokes ctrl+shift+ redo the last keystroke or group of keystrokes run module first program start idle and open up new window (choose new window under the file menutype in the following program temp eval(input'enter temperature in celsius')print'in fahrenheitthat is ' / *temp+ thenunder the run menuchoose run module (or press idle will ask you to save the fileand you should do so be sure to append py to the filename as idle will not automatically append it this will tell idle to use colors to make your program easier to read once you've saved the programit will run in the shell window the program will ask you for temperature type in and press enter the program' output looks something like thisenter temperature in celsius in fahrenheitthat is let' examine how the program does what it does the first line asks the user to enter temperature the input function' job is to ask the user to type something in and to capture what the user types the part in quotes is the prompt that the user sees it is called string and it will appear to the program' user exactly as it appears in the code itself the eval function is something we use herebut it won' be clear exactly why until later so for nowjust remember that we use it when we're getting numerical input we need to give name to the value that the user enters so that the program can remember it and use it in the second line the name we use is temp and we use the equals sign to assign the user' value to temp the second line uses the print function to print out the conversion the part in quotes is another string and will appear to your program' user exactly as it appears in quotes here the second
9,160
argument to the print function is the calculation python will do the calculation and print out the numerical result this program may seem too short and simple to be of much usebut there are many websites that have little utilities that do similar conversionsand their code is not much more complicated than the code here second program entershere is program that computes the average of two numbers that the user num eval(input'enter the first number')num eval(input'enter the second number')print'the average of the numbers you entered is '(num +num )/ for this program we need to get two numbers from the user there are ways to do that in one linebut for now we'll keep things simple we get the numbers one at time and give each number its own name the only other thing to note is the parentheses in the average calculation this is because of the order of operations all multiplications and divisions are performed before any additions and subtractionsso we have to use parentheses to get python to do the addition first typing things in case case matters to pythonprintprintand print are all different things for nowstick with lowercase as most python statements are in lowercase spaces spaces matter at the beginning of linesbut not elsewhere for examplethe code below will not work temp eval(input'enter temperature in celsius')print'in fahrenheitthat is ' / *temp+ python uses indentation of lines for things we'll learn about soon on the other handspaces in most other places don' matter for instancethe following lines have the same effectprint'hello world'print 'hello world'print'hello worldbasicallycomputers will only do what you tell themand they often take things very literally python itself totally relies on things like the placement of commas and parentheses so it knows what' what it is not very good at figuring out what you meanso you have to be precise it will be very frustrating at firsttrying to get all of the parentheses and commas in the right placesbut after while it will become more natural stilleven after you've programmed for long timeyou will still miss something fortunatelythe python interpreter is pretty good about helping you find your mistakes
9,161
getting started getting input the input function is simple way for your program to get information from people using your program here is an examplename input'enter your name'print'hello'namethe basic structure is variable name input(message to userthe above works for getting text from the user to get numbers from the user to use in calculationswe need to do something extra here is an examplenum eval(input'enter number')print'your number squared'num*numthe eval function converts the text entered by the user into number one nice feature of this is you can enter expressionslike * + and eval will compute them for you note if you run your program and nothing seems to be happeningtry pressing enter there is bit of glitch in idle that occasionally happens with input statements printing here is simple exampleprint'hi there 'the print function requires parenthesis around its arguments in the program aboveits only argument is the string 'hi thereanything inside quotes will (with few exceptionsbe printed exactly as it appears in the followingthe first statement will output + while the second will output print' + 'print( + to print several things at onceseparate them by commas python will automatically insert spaces between them below is an example and the output it produces print'the value of + is ' + print' ' 'xyz ' the value of + is xyz
9,162
optional arguments there are two optional arguments to the print function they are not overly important at this stage of the gameso you can safely skip over this sectionbut they are useful for making your output look nice sep python will insert space between each of the arguments of the print function there is an optional argument called sepshort for separatorthat you can use to change that space to something else for exampleusing sep=':would separate the arguments by colon and sep='##would separate the arguments by two pound signs one particularly useful possibility is to have nothing inside the quotesas in sep='this says to put no separation between the arguments here is an example where sep is useful for getting the output to look niceprint 'the value of + is ' + 'print 'the value of + is ' + 'sep''the value of + is the value of + is end the print function will automatically advance to the next line for instancethe following will print on two linesprint'on the first line 'print'on the second line 'on the first line on the second line there is an optional argument called end that you can use to keep the print function from advancing to the next line here is an exampleprint'on the first line 'end''print'on the second line 'on the first lineon the second line of coursethis could be accomplished better with single printbut we will see later that there are interesting uses for the end argument variables looking back at our first programwe see the use of variable called temp
9,163
getting started temp eval(input'enter temperature in celsius')print'in fahrenheitthat is ' / *temp+ one of the major purposes of variable is to remember value from one part of program so that it can be used in another part of the program in the case abovethe variable temp stores the value that the user enters so that we can do calculation with it in the next line in the example belowwe perform calculation and need to use the result of the calculation in several places in the program if we save the result of the calculation in variablethen we only need to do the calculation once this also helps to make the program more readable temp eval(input'enter temperature in celsius')f_temp / *temp+ print'in fahrenheitthat is 'f_tempif f_temp print'that temperature is above the boiling point 'if f_temp print'that temperature is below the freezing point 'we haven' discussed if statements yetbut they do exactly what you think they do second example here is another example with variables before reading ontry to figure out what the values of and will be after the code is executed = = = + = + = = after these four lines of code are executedx is is and is one way to understand something like this is to take it one line at time this is an especially useful technique for trying to understand more complicated chunks of code here is description of what happens in the code above starts with the value and starts with the value in line variable is created to equal +ywhich is then the value of is changed to equal one more than it currently equalschanging it from to nextx is changed to the current value of ywhich is finallyy is changed to note that this does not affect so at the endx is is and is
9,164
variable names there are just couple of rules to follow when naming your variables variable names can contain lettersnumbersand the underscore variable names cannot contain spaces variable names cannot start with number case matters--for instancetemp and temp are different it helps make your program more understandable if you choose names that are descriptivebut not so long that they clutter up your program exercises print box like the one below ************************************************************************ print box like the one below ************************************ print triangle like the one below ****** write program that computes and prints the result of it is roughly ask the user to enter number print out the square of the numberbut use the sep optional argument to print it out in full sentence that ends in period sample output is shown below enter number the square of is
9,165
getting started ask the user to enter number use the sep optional argument to print out and each separated by three dasheslike below enter number --- --- --- --- write program that asks the user for weight in kilograms and converts it to pounds there are pounds in kilogram write program that asks the user to enter three numbers (use three separate input statementscreate variables called total and average that hold the sum and average of the three numbers and print out the values of total and average lot of cell phones have tip calculators write one ask the user for the price of the meal and the percent tip they want to leave then print both the tip amount and the total bill with the tip included
9,166
for loops probably the most powerful thing about computers is that they can repeat things over and over very quickly there are several ways to repeat things in pythonthe most common of which is the for loop examples example the following program will print hello ten timesfor in range( )print'hello 'the structure of for loop is as followsfor variable name in rangenumber of times to repeat )statements to be repeated the syntax is important here the word for must be in lowercasethe first line must end with colonand the statements to be repeated must be indented indentation is used to tell python which statements will be repeated example the program below asks the user for number and prints its squarethen asks for another number and prints its squareetc it does this three times and then prints that the loop is done for in range( )num eval(input'enter number')print 'the square of your number is 'num*numprint'the loop is now done '
9,167
for loops enter number the square of your number is enter number the square of your number is enter number the square of your number is the loop is now done since the second and third lines are indentedpython knows that these are the statements to be repeated the fourth line is not indentedso it is not part of the loop and only gets executed onceafter the loop has completed looking at the above examplewe see where the term for loop comes fromwe can picture the execution of the code as starting at the for statementproceeding to the second and third linesthen looping back up to the for statement example the program below will print athen bthen it will alternate ' and ' five times and then finish with the letter once print' 'print' 'for in range( )print' 'print' 'print' 'the first two print statements get executed onceprinting an followed by nextthe ' and ' alternate five times note that we don' get five ' followed by five ' the way the loop works is we print cthen dthen loop back to the start of the loop and print and another detc once the program is done looping with the ' and 'sit prints one example if we wanted the above program to print five ' followed by five 'sinstead of alternating ' and 'swe could do the followingprint' 'print' 'for in range( )print' 'for in range( )print' 'print' '
9,168
the loop variable there is one part of for loop that is little trickyand that is the loop variable in the example belowthe loop variable is the variable the output of this program will be the numbers each printed on its own line for in range( )print(iwhen the loop first startspython sets the variable to each time we loop back uppython increases the value of by the program loops timeseach time increasing the value of by until we have looped times at this point the value of is you may be wondering why starts with instead of wellthere doesn' seem to be any really good reason why other than that starting at was useful in the early days of computing and it has stuck with us in fact most things in computer programming start at instead of this does take some getting used to since the loop variableigets increased by each time through the loopit can be used to keep track of where we are in the looping process consider the example belowfor in range( )print( + '-hello ' -hello -hello -hello names there' nothing too special about the name for our variable the programs below will have the exact same result for in range( )print(ifor wacky_name in range( )print(wacky_nameit' convention in programming to use the letters ijand for loop variablesunless there' good reason to give the variable more descriptive name the range function the value we put in the range function determines how many times we will loop the way range works is it produces list of numbers from zero to the value minus one for instancerange( produces five values and
9,169
for loops if we want the list of values to start at value other than we can do that by specifying the starting value the statement range( , will produce the list this brings up one quirk of the range function--it stops one short of where we think it should if we wanted the list to contain the numbers through (including )then we would have to do range( , another thing we can do is to get the list of values to go up by more than one at time to do thiswe can specify an optional step as the third argument the statement range( , , will step through the list by twosproducing to get the list of values to go backwardswe can use step of - for instancerange( , ,- will produce the values in that order (note that the range function stops one short of the ending value here are few more examplesstatement values generated range( , , , , , , , , , range( , , , , , , , , , range( , , , , range( , , , , , , range( , ,- , , , , , , here is an example program that counts down from and then prints message for in range( , ,- )print(iend'print'blast off!' blast off!!the end=just keeps everything on the same line trickier example let' look at problem where we will make use of the loop variable the program below prints rectangle of stars that is rows tall and rows wide for in range( )print''* the rectangle produced by this code is shown below on the left the code '*'* is something we'll cover in section it just repeats the asterisk character six times **************************
9,170
suppose we want to make triangle instead we can accomplish this with very small change to the rectangle program looking at the programwe can see that the for loop will repeat the print statement four timesmaking the shape four rows tall it' the that will need to change the key is to change the to + each time through the loop the program will now print + stars instead of stars the loop counter variable runs through the values and using it allows us to vary the number of stars here is triangle programfor in range( )print''*( + ) exercises write program that prints your name times write program to fill the screen horizontally and vertically with your name [hintadd the option end='into the print function to fill the screen horizontally write program that outputs linesnumbered to each with your name on it the output should look like the output below your name your name your name your name your name write program that prints out list of the integers from to and their squares the output should look like this -- -- -- -- write program that uses for loop to print the numbers write program that uses for loop to print the numbers write program that uses exactly four for loops to print the sequence of letters below aaaaaaaaaabbbbbbbcdcdcdcdeffffffg write program that asks the user for their name and how many times to print it the program should print out the user' name the specified number of times
9,171
for loops the fibonacci numbers are the sequence belowwhere the first two numbers are and each number thereafter is the sum of the two preceding numbers write program that asks the user how many fibonacci numbers to print and then prints that many use for loop to print box like the one below allow the user to specify how wide and how high the box should be [hintprint('*'* prints ten asterisks ************************************************************************ use for loop to print box like the one below allow the user to specify how wide and how high the box should be ************************************ use for loop to print triangle like the one below allow the user to specify how high the triangle should be ****** use for loop to print an upside down triangle like the one below allow the user to specify how high the triangle should be ****** use for loops to print diamond like the one below allow the user to specify how high the diamond should be ******************
9,172
write program that prints giant letter like the one below allow the user to specify how large the letter should be ****
9,173
for loops
9,174
numbers this focuses on numbers and simple mathematics in python integers and decimal numbers because of the way computer chips are designedintegers and decimal numbers are represented differently on computers decimal numbers are represented by what are called floating point numbers the important thing to remember about them is you typically only get about or so digits of precision it would be nice if there were no limit to the precisionbut calculations run lot more quickly if you cut off the numbers at some point on the other handintegers in python have no restrictions they can be arbitrarily large for decimal numbersthe last digit is sometimes slightly off due to the fact that computers work in binary (base whereas our human number system is base as an examplemathematicallywe know that the decimal expansion of / is with the threes repeating forever but when we type / into the python shellwe get this is called roundoff error for most practical purposes this is not too big of dealbut it actually can cause problems for some mathematical and scientific calculations if you really need more precisionthere are ways see section math operators here is list of the common operators in python
9,175
numbers operator description addition subtraction multiplication division *exponentiation /integer division modulo (remainderexponentiation python uses *for exponentiation the caret^is used for something else integer division the integer division operator//requires some explanation basicallyfor positive numbers it behaves like ordinary division except that it throws away the decimal part of the result for instancewhile / is we have // equal to we will see uses for this operator later note that in many other programming languages and in older versions of pythonthe usual division operator actually does integer division on integers modulo the modulo operator%returns the remainder from division for instancethe result of % is because is the remainder when is divided by this operation is surprisingly useful for instancea number is divisible by precisely when it leaves remainder of when divided by thus to check if numbernis evensee if % is equal to to check if is divisible by see if % is one use of this is if you want to schedule something in loop to happen only every other time through the loopyou could check to see if the loop variable modulo is equal to and if it isthen do that something the modulo operator shows up surprisingly often in formulas if you need to "wrap aroundand come back to the startthe modulo is useful for examplethink of clock if you go six hours past 'clockthe result is 'clock mathematicallythis can be accomplished by doing modulo by that is( + )% is equal to as another exampletake game with players through say you have variable player that keeps track of the current player after player goesit' player ' turn again the modulo operator can be used to take care of thisplayer player% + when player is player% will be and expression will set player to
9,176
order of operations exponentiation gets done firstfollowed by multiplication and division (including /and %)and addition and subtraction come last the classic math class mnemonicpemdas (please excuse my dear aunt sally)might be helpful this comes into play in calculating an average say you have three variables xyand zand you want to calculate the average of their values to expression + + / would not work because xy+ division comes before additionyou would actually be calculating instead of this is easily fixed by using parentheses( + + )/ in generalif you're not sure about somethingadding parentheses might help and usually doesn' do any harm random numbers to make an interesting computer gameit' good to introduce some randomness into it python comes with modulecalled randomthat allows us to use random numbers in our programs before we get to random numberswe should first explain what module is the core part of the python language consists of things like for loopsif statementsmath operatorsand some functionslike print and input everything else is contained in modulesand if we want to use something from module we have to first import it--that istell python that we want to use it at this pointthere is only one functioncalled randintthat we will need from the random module to load this functionwe use the following statementfrom random import randint using randint is simplerandint( ,bwill return random integer between and including both and (note that randint includes the right endpoint unlike the range functionhere is short examplefrom random import randint randint( , print' random number between and 'xa random number between and the random number will be different every time we run the program math functions the math module python has module called math that contains familiar math functionsincluding sincostanexploglog factorialsqrtfloorand ceil there are also the inverse trig functionshyperbolic functionsand the constants pi and here is short example
9,177
numbers from math import sinpi print'pi is roughly 'piprint'sin( 'sin( )pi is roughly sin( built-in math functions there are two built in math functionsabs (absolute valueand round that are available without importing the math module here are some examplesprint(abs(- )print(round( )print(round( - ) the round function takes two argumentsthe first is the number to be rounded and the second is the number of decimal places to round to the second argument can be negative getting help from python there is documentation built into python to get help on the math modulefor examplego to the python shell and type the following two linesimport math dir(math['__doc__''__name__''__package__''acos''acosh''asin''asinh''atan''atan ''atanh''ceil''copysign''cos''cosh''degrees'' ''exp''fabs''factorial''floor''fmod''frexp''fsum''hypot''isinf''isnan''ldexp''log''log ''log ''modf''pi''pow''radians''sin''sinh''sqrt''tan''tanh''trunc'this gives list of all the functions and variables in the math module you can ignore all of the ones that start with underscores to get help on specific functionsay the floor functionyou can type help(math floortyping help(mathwill give you help for everything in the math module using the shell as calculator the python shell can be used as very handy and powerful calculator here is an example session
9,178
** for in range( , ) / ** from math import factorial( the second example here sums the numbers / / / the result is stored in the variable to inspect the value of that variablejust type its name and press enter inspecting variables is useful for debugging your programs if program is not working properlyyou can type your variable names into the shell after the program has finished to see what their values are the statement from math importimports every function from the math modulewhich can make the shell lot like scientific calculator note under the shell menuselect restart shell if you want to clear the values of all the variables exercises write program that generates and prints random integerseach between and write program that generates random numberx between and random number between and and computes write program that generates random number between and and prints your name that many times write program that generates random decimal number between and with two decimal places of accuracy examples are and write program that generates random numbers such that the first number is between and the second is between and the third is between and and the last is between and |xy write program that asks the user to enter two numbersx and and computes xy write program that asks the user to enter an angle between - and using an expression with the modulo operatorconvert the angle to its equivalent between and
9,179
numbers write program that asks the user for number of seconds and prints out how many minutes and seconds that is for instance seconds is minutes and seconds [hintuse the /operator to get minutes and the operator to get seconds write program that asks the user for an hour between and and for how many hours in the future they want to go print out what the hour will be that many hours into the future an example is shown below enter hour how many hours ahead new hour 'clock (aone way to find out the last digit of number is to mod the number by write program that asks the user to enter power then find the last digit of raised to that power (bone way to find out the last two digits of number is to mod the number by write program that asks the user to enter power then find the last two digits of raised to that power (cwrite program that asks the user to enter power and how many digits they want find the last that many digits of raised to the power the user entered write program that asks the user to enter weight in kilograms the program should convert it to poundsprinting the answer rounded to the nearest tenth of pound write program that asks the user for number and prints out the factorial of that number write program that asks the user for number and then prints out the sinecosineand tangent of that number write program that asks the user to enter an angle in degrees and prints out the sine of that angle write program that prints out the sine and cosine of the angles ranging from to in increments each result should be rounded to decimal places sample output is shown below -- -- -- --- below is described how to find the date of easter in any year despite its intimidating appearancethis is not hard problem note that is the floor functionwhich for positive numbers just drops the decimal part of the number for instance the floor function is part of the math module century ( '
9,180
year (all four digitsm ( + mod ( mod mod mod mod ( mmod ( nmod easter is either march ( eor april ( there is an exception if and in this caseeaster falls one week earlier on april there is another exception if and or in this caseeaster falls one week earlier on april write program that asks the user to enter year and prints out the date of easter in that year (see tattersallelementary number theory in nine nd ed page year is leap year if it is divisible by except that years divisible by are not leap years unless they are also divisible by ask the user to enter yearandusing the /operatordetermine how many leap years there have been between and that year write program that given an amount of change less than $ will print out exactly how many quartersdimesnickelsand pennies will be needed to efficiently make that change [hintthe /operator may be useful write program that draws "modular rectangleslike the ones below the user specifies the width and height of the rectangleand the entries start at and increase typewriter fashion from left to right and top to bottombut are all done mod below are examples of rectangle and
9,181
numbers
9,182
if statements quite often in programs we only want to do something provided something else is true python' if statement is what we need simple example let' try guess- -number program the computer picks random numberthe player tries to guessand the program tells them if they are correct to see if the player' guess is correctwe need something newcalled an if statement from random import randint num randint( , guess eval(input'enter your guess')if guess==numprint'you got it'the syntax of the if statement is lot like the for statement in that there is colon at the end of the if condition and the following line or lines are indented the lines that are indented will be executed only if the condition is true once the indentation is done withthe if block is concluded the guess- -number game worksbut it is pretty simple if the player guesses wrongnothing happens we can add to the if statement as followsif guess==numprint'you got it'elseprint'sorry the number is 'numwe have added an else statementwhich is like an "otherwise
9,183
if statements conditional operators the comparison operators are ==>=<=and !that last one is for not equals here are few examplesexpression description if > if is greater than if >= if is greater than or equal to if == if is if != if is not there are three additional operators used to construct more complicated conditionsandorand not here are some examplesif grade>= and grade< print'your grade is 'if score> or time> print'game over 'if not (score> or time> )print'game continues 'order of operations in terms of order of operationsand is done before orso if you have complicated condition that contains bothyou may need parentheses around the or condition think of and as being like multiplication and or as being like addition here is an exampleif (score and turns_remaining== print'game over ' common mistakes mistake the operator for equality consists of two equals signs it is really common error to forget one of the equals signs incorrect correct if = if == mistake common mistake is to use and where or is needed or vice-versa consider the following if statementsif > and < if > or <
9,184
the first statement is the correct one if is any value between and then the statement will be true the idea is that has to be both greater than and less than on the other handthe second statement is not what we want because for it to be trueeither has to be greater than or has to be less than but every number satisfies this the lesson here is if your program is not working correctlycheck your and' and or' mistake another very common mistake is to write something like belowif grade>= and < this will lead to syntax error we have to be explicit the correct statement is if grade>= and grade< on the other handthere is nice shortcut that does work in python (though not in many other programming languages)if <=grade< elif simple use of an if statement is to assign letter grades suppose that scores and above are 'sscores in the are ' are ' are 'sand anything below is an here is one way to do thisgrade eval(input'enter your score')if grade>= print' 'if grade>= and grade< print' 'if grade>= and grade< print' 'if grade>= and grade< print' 'if grade< print' 'the code above is pretty straightforward and it works howevera more elegant way to do it is shown below grade eval(input'enter your score')if grade>= print' 'elif grade>= print' 'elif grade>= print' '
9,185
if statements elif grade>= print' 'elseprint' 'with the separate if statementseach condition is checked regardless of whether it really needs to be that isif the score is the first program will print an but then continue on and check to see if the score is bcetc which is bit of waste using elifas soon as we find where the score matcheswe stop checking conditions and skip all the way to the end of the whole block of statements an added benefit of this is that the conditions we use in the elif statements are simpler than in their if counterparts for instancewhen using elifthe second part of the second if statement conditiongrade< becomes unnecessary because the corresponding elif does not have to worry about score of or aboveas such score would have already been caught by the first if statement you can get along just fine without elifbut it can often make your code simpler exercises write program that asks the user to enter length in centimeters if the user enters negative lengththe program should tell the user that the entry is invalid otherwisethe program should convert the length to inches and print out the result there are centimeters in an inch ask the user for temperature then ask them what unitscelsius or fahrenheitthe temperature is in your program should convert the temperature to the other unit the conversions are and ( ask the user to enter temperature in celsius the program should print message based on the temperatureif the temperature is less than - print that the temperature is invalid because it is below absolute zero if it is exactly - print that the temperature is absolute if the temperature is between - and print that the temperature is below freezing if it is print that the temperature is at the freezing point if it is between and print that the temperature is in the normal range if it is print that the temperature is at the boiling point if it is above print that the temperature is above the boiling point write program that asks the user how many credits they have taken if they have taken or lessprint that the student is freshman if they have taken between and print that they are sophomore the range for juniors is to and for seniors it is and over
9,186
generate random number between and ask the user to guess the number and print message based on whether they get it right or not store charges $ per item if you buy less than items if you buy between and itemsthe cost is $ per item if you buy or more itemsthe cost is $ per item write program that asks the user how many items they are buying and prints the total cost write program that asks the user for two numbers and prints close if the numbers are within of each other and not close otherwise year is leap year if it is divisible by except that years divisible by are not leap years unless they are also divisible by write program that asks the user for year and prints out whether it is leap year or not write program that asks the user to enter number and prints out all the divisors of that number [hintthe operator is used to tell if number is divisible by something see section write multiplication game program for kids the program should give the player ten randomly generated multiplication questions to do after eachthe program should tell them whether they got it right or wrong and what the correct answer is question rightquestion wrong the answer is question right write program that asks the user for an hour between and asks them to enter am or pmand asks them how many hours into the future they want to go print out what the hour will be that many hours into the futureprinting am or pm as appropriate an example is shown below enter hour am ( or pm ( ) how many hours ahead new hour pm jar of halloween candy contains an unknown amount of candy and if you can guess exactly how much candy is in the bowlthen you win all the candy you ask the person in charge the followingif the candy is divided evenly among peoplehow many pieces would be left overthe answer is pieces you then ask about dividing the candy evenly among peopleand the amount left over is pieces finallyyou ask about dividing the candy evenly among peopleand the amount left over is pieces by looking at the bowlyou can tell that there are less than pieces write program to determine how many pieces are in the bowl
9,187
if statements write program that lets the user play rock-paper-scissors against the computer there should be five roundsand after those five roundsyour program should print out who won and lost or that there is tie
9,188
miscellaneous topics this consists of several common techniques and some other useful information counting very often we want our programs to count how many times something happens for instancea video game may need to keep track of how many turns player has usedor math program may want to count how many numbers have special property the key to counting is to use variable to keep the count example this program gets numbers from the user and counts how many of those numbers are greater than count for in range( )num eval(input'enter number')if num> count=count+ print'there are 'count'numbers greater than 'think of the count variable as if we are keeping tally on piece of paper every time we get number larger than we add to our tally in the programthis is accomplished by the line count=count+ the first line of the programcount= is important without itthe python interpreter would get to the count=count+ line and spit out an error saying something about not knowing what count is this is because the first time the program gets to this lineit tries to do what it saystake the old value of countadd to itand store the result in count but the first time the program gets therethere is no old value of count to useso the python interpreter doesn' know what to do to avoid the errorwe need to define countand that is what the first
9,189
miscellaneous topics line does we set it to to indicate that at the start of the program no numbers greater than have been found counting is an extremely common thing the two things involved are count= -start the count at count=count+ -increase the count by example this modification of the previous example counts how many of the numbers the user enters are greater than and also how many are equal to to count two things we use two count variables count count for in range( )num eval(input'enter number')if num> count =count + if num== count =count + print'there are 'count 'numbers greater than 'print'there are 'count 'zeroes 'example next we have slightly trickier example this program counts how many of the squares from to end in count for in range( , )if ( ** )% == count count print(counta few notes herefirstbecause of the aforementioned quirk of the range functionwe need to use range( , to loop through the numbers through the looping variable takes on those valuesso the squares from to are represented by ** nextto check if number ends in nice mathematical trick is to check if it leaves remainder of when divided by the modulo operator%is used to get the remainder summing closely related to counting is summingwhere we want to add up bunch of numbers
9,190
example this program will add up the numbers from to the way this works is that each time we encounter new numberwe add it to our running totals for in range( , ) print'the sum is 'sexample this program that will ask the user for numbers and then computes their average for in range( )num eval(input'enter number') num print'the average is ' / example common use for summing is keeping score in game near the beginning of the game we would set the score variable equal to then when we want to add to the score we would do something like belowscore score swapping quite often we will want to swap the values of two variablesx and it would be tempting to try the followingx but this will not work suppose is and is the first line will set to which is goodbut then the second line will set to also because is now the trick is to use third variable to save the value of xhold hold in many programming languagesthis is the usual way to swap variables pythonhoweverprovides nice shortcutx, , we will learn later exactly why this works for nowfeel free to use whichever method you prefer the latter methodhoweverhas the advantage of being shorter and easier to understand
9,191
miscellaneous topics flag variables flag variable can be used to let one part of your program know when something happens in another part of the program here is an example that determines if number is prime num eval(input'enter number')flag for in range( ,num)if num% == flag if flag== print'not prime 'elseprint'prime 'recall that number is prime if it has no divisors other than and itself the way the program above works is flag starts off at we then loop from to num- if one of those values turns out to be divisorthen flag gets set to once the loop is finishedwe check to see if the flag got set or not if it didwe know there was divisorand num isn' prime otherwisethe number must be prime maxes and mins common programming task is to find the largest or smallest value in series of values here is an example where we ask the user to enter ten positive numbers and then we print the largest one largest eval(input'enter positive number')for in range( )num eval(input'enter positive number')if num>largestlargest=num print'largest number'largestthe key here is the variable largest that keeps track of the largest number found so far we start by setting it equal to the user' first number thenevery time we get new number from the userwe check to see if the user' number is larger than the current largest value (which is stored in largestif it isthen we set largest equal to the user' number ifinsteadwe want the smallest valuethe only change necessary is that becomes <though it would also be good to rename the variable largest to smallest later onwhen we get to listswe will see shorter way to find the largest and smallest valuesbut the technique above is useful to know since you may occasionally run into situations where the list way won' do everything you need it to do
9,192
comments comment is message to someone reading your program comments are often used to describe what section of code does or how it worksespecially with tricky sections of code comments have no effect on your program single-line comments for single-line commentuse the character slightly sneaky way to get two values at once num num eval(input'enter two numbers separated by commas')you can also put comments at the end of linecount count each divisor contributes two the count multi-line comments for comments that span several linesyou can use triple quotes ""program namehello world authorbrian heinold date""print'hello world 'one nice use for the triple quotes is to comment out parts of your code often you will want to modify your program but don' want to delete your old code in case your changes don' work you could comment out the old code so that it is still there if you need itand it will be ignored when your new program is run here is simple example""print('this line and the next are inside comment 'print('these lines will not get executed '""print'this line is not in comment and it will be executed ' simple debugging here are two simple techniques for figuring out why program is not working use the python shell after your program has runyou can type in the names of your program' variables to inspect their values and see which ones have the values you expect them to have and which don' you can also use the shell to type in small sections of your program and see if they are working add print statements to your program you can add these at any point in your program to see what the values of your variables are you can also add print statement to see if point in your code is even being reached for instanceif you think you might have an error in
9,193
miscellaneous topics condition of an if statementyou can put print statement into the if block to see if the condition is being triggered here is an example from the part of the primes program from earlier in this we put print statement into the for loop to see exactly when the flag variable is being setflag num eval(input'enter number')for in range( ,num)if num% == flag print(iflag an empty input statementlike belowcan be used to pause your program at specific pointinput( example programs it is valuable skill is to be able to read code in this section we will look in depth at some simple programs and try to understand how they work example the following program prints hello random number of times between and from random import randint rand_num randint( , for in range(rand_num)print'hello 'the first line in the program is the import statement this just needs to appear onceusually near the beginning of your program the next line generates random number between and thenremember that to repeat something specified number of timeswe use for loop to repeat something timeswe would use range( in our for loop to repeat something timeswe would use range( to repeat something random number of timeswe can use range(rand_num)where rand_num is variable holding random number although if we wantwe can skip the variable and put the randint statement directly in the range functionas shown below from random import randint for in range(randint( , ))print'hello '
9,194
example compare the following two programs from random import randint from random import randint rand_num randint( , for in range( )print'hello '*rand_numfor in range( )rand_num randint( , print'hello '*rand_numhello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello the only difference between the programs is in the placement of the rand_num statement in the first programit is located outside of the for loopand this means that rand_num is set once at the beginning of the program and retains that same value for the life of the program thus every print statement will print hello the same number of times in the second programthe rand_num statement is within the loop right before each print statementrand_num is assigned new random numberand so the number of times hello is printed will vary from line to line example let us write program that generates random numbers between and and counts how many of them are multiples of here are the things we will needbecause we are using random numbersthe first line of the program should import the random module we will require for loop to run times inside the loopwe will need to generate random numbercheck to see if it is divisible by and if soadd to the count since we are countingwe will also need to set the count equal to before we start counting to check divisibility by we use the modulo%operator when we put this all togetherwe get the followingfrom random import randint count for in range( )num randint( if num% == count=count+ print'number of multiples of 'count
9,195
miscellaneous topics indentation matters common mistake is incorrect indentation suppose we take the above and indent the last line the program will still runbut it won' run as expected from random import randint count for in range( )num randint( if num% == count=count+ print'number of multiples of 'countwhen we run itit outputs whole bunch of numbers the reason for this is that by indenting the print statementwe have made it part of the for loopso the print statement will be executed , times suppose we indent the print statement one step furtherlike below from random import randint count for in range( )num randint( if num% == count=count+ print'number of multiples of 'countnownot only is it part of the for loopbut it is also part of the if statement what will happen is every time we find new multiple of we will print the count neither thisnor the previous exampleis what we want we just want to print the count once at the end of the programso we don' want the print statement indented at all exercises write program that counts how many of the squares of the numbers from to end in write program that counts how many of the squares of the numbers from to end in and how many end in write program that asks the user to enter value nand then computes ( ln(nthe ln function is log in the math module write program to compute the sum
9,196
write program that asks the user to enter number and prints the sum of the divisors of that number the sum of the divisors of number is an important function in number theory number is called perfect number if it is equal to the sum of all of its divisorsnot including the number itself for instance is perfect number because the divisors of are and as another example is perfect number because its divisors are and however is not perfect number because its divisors are and write program that finds all four of the perfect numbers that are less than an integer is called squarefree if it is not divisible by any perfect squares other than for instance is squarefree because its divisors are and and none of those numbers (except is perfect square on the other hand is not squarefree because it is divisible by which is perfect square write program that asks the user for an integer and tells them if it is squarefree or not write program that swaps the values of three variables and so that gets the value of gets the value of and gets the value of write program to count how many integers from to are not perfect squaresperfect cubesor perfect fifth powers ask the user to enter test scores write program to do the following(aprint out the highest and lowest scores (bprint out the average of the scores (cprint out the second largest score (dif any of the scores is greater than then after all the scores have been enteredprint message warning the user that value over has been entered (edrop the two lowest scores and print out the average of the rest of them write program that computes the factorial of number the factorialn!of number is the product of all the integers between and nincluding for instance [hinttry using multiplicative equivalent of the summing technique write program that asks the user to guess random number between and if they guess rightthey get points added to their scoreand they lose point for an incorrect guess give the user five numbers to guess and print their score after all the guessing is done in the last there was an exercise that asked you to create multiplication game for kids improve your program from that exercise to keep track of the number of right and wrong answers at the end of the programprint message that varies depending on how many questions the player got right this exercise is about the well-known monty hall problem in the problemyou are contestant on game show the hostmonty hallshows you three doors behind one of those doors is prizeand behind the other two doors are goats you pick door monty hallwho
9,197
miscellaneous topics knows behind which door the prize liesthen opens up one of the doors that doesn' contain the prize there are now two doors leftand monty gives you the opportunity to change your choice should you keep the same doorchange doorsor does it not matter(awrite program that simulates playing this game times and calculates what percentage of the time you would win if you switch and what percentage of the time you would win by not switching (btry the above but with four doors instead of three there is still only one prizeand monty still opens up one door and then gives you the opportunity to switch
9,198
strings strings are data type in python for dealing with text python has number of powerful features for manipulating strings basics creating string string is created by enclosing text in quotes you can use either single quotes'or double quotesa triple-quote can be used for multi-line strings here are some exampless 'hello "hellom """this is long string that is spread across two lines ""input recall from that when getting numerical input we use an eval statement with the input statementbut when getting textwe do not use eval the difference is illustrated belownum eval(input'enter number')string input'enter string'empty string the empty string 'is the string equivalent of the number it is string with nothing in it we have seen it beforein the print statement' optional argumentsep='length to get the length of string (how many characters it has)use the built-in function len for examplelen('hello'is
9,199
strings concatenation and repetition the operators and can be used on strings the operator combines two strings this operation is called concatenation the repeats string certain number of times here are some examples expression result 'ab'+'cd'abcd' '+' '+' ' 'hi'* 'hihihihiexample if we want to print long row of dasheswe can do the following print''* example the operator can be used to build up stringpiece by pieceanalogously to the way we built up counts and sums in sections and here is an example that repeatedly asks the user to enter letter and builds up string consisting of only the vowels that the user entered 'for in range( ) input'enter letter'if =' or =' or =' or =' or =' ' print(sthis technique is very useful the in operator the in operator is used to tell if string contains something for exampleif ' in stringprint'your string contains the letter 'you can combine in with the not operator to tell if string does not contain somethingif 'not in stringprint'your string does not contain any semicolons 'example in the previous section we had the long if condition if =' or =' or =' or =' or =' 'using the in operatorwe can replace that statement with the followingif in 'aeiou '