id
int64
0
25.6k
text
stringlengths
0
4.59k
9,300
gui programming with tkinter label grid(row= column= label grid(row= column= label grid(row= column= columnspan= label grid(row= column= label grid(row= column= label label label label label spacing to add extra space between widgetsthere are optional arguments padx and pady important note any time you create widgetto place it on the screen you need to use grid (or one of its cousinslike packwhich we will talk about laterotherwise it will not be visible entry boxes entry boxes are way for your gui to get text input the following example creates simple entry box and places it on the screen entry entry(entry grid(row= column= most of the same options that work with labels work with entry boxes (and most of the other widgets we will talk aboutthe width option is particularly helpful because the entry box will often be wider than you need getting text to get the text from an entry boxuse its get method this will return string if you need numerical datause eval (or int or floaton the string here is simple example that gets text from an entry box named entry string_value entry get(num_value eval(entry get()deleting text to clear an entry boxuse the followingentry delete( ,endinserting text to insert text into an entry boxuse the followingentry insert( 'hello ' buttons the following example creates simple button
9,301
ok_button button(text'ok 'to get the button to do something when clickeduse the command argument it is set to the name of functioncalled callback function when the button is clickedthe callback function is called here is an examplefrom tkinter import def callback()label configure(text'button clicked 'root tk(label label(text'not clicked 'button button(text'click me 'command=callbacklabel grid(row= column= button grid(row= column= mainloop(when the program startsthe label says click me when the button is clickedthe callback function callback is calledwhich changes the label to say button clicked lambda trick sometimes we will want to pass information to the callback functionlike if we have several buttons that use the same callback function and we want to give the function information about which button is being clicked here is an example where we create buttonsone for each letter of the alphabet rather than use separate button(statements and different functionswe use list and one function from tkinter import alphabet 'abcdefghijklmnopqrstuvwxyz def callback( )label configure(text'button {clicked format(alphabet[ ])root tk(label label(label grid(row= column= columnspan= buttons [ ]* create list to hold buttons for in range( )buttons[ibutton(text=alphabet[ ]command lambda =icallback( )
9,302
gui programming with tkinter buttons[igrid(row= column=imainloop(we note few things about this program firstwe set buttons=[ ]* this creates list with things in it we don' really care what thoset things are because they will be replaced with buttons an alternate way to create the list would be to set buttons=[and use the append method we only use one callback function and it has one argumentwhich indicates which button was clicked as far as the lambda trick goeswithout getting into the detailscommand=callback(idoes not workand that is why we resort to the lambda trick you can read more about lambda in section an alternate approach is to use classes global variables let' say we want to keep track of how many times button is clicked an easy way to do this is to use global variable as shown below from tkinter import def callback()global num_clicks num_clicks num_clicks label configure(text'clicked {times format(num_clicks)num_clicks root tk(label label(text'not clicked 'button button(text'click me 'command=callbacklabel grid(row= column= button grid(row= column= mainloop(we will be using few global variables in our gui programs using global variables unnecessarilyespecially in long programscan cause difficult to find errors that make programs hard to maintain
9,303
but in the short programs that we will be writingwe should be okay object-oriented programming provides an alternative to global variables tic-tac-toe using tkinterin only about lines we can make working tic-tac-toe programfrom tkinter import def callback( , )global player if player =' ' [ ][cconfigure(text ' 'player ' elseb[ ][cconfigure(text ' 'player ' root tk( [[ , , ][ , , ][ , , ]for in range( )for in range( ) [ ][jbutton(font='verdana ' )width= bg'yellow 'command lambda = , =jcallback( , ) [ ][jgrid(row icolumn jplayer ' mainloop(the program worksthough it does have few problemslike letting you change cell that already has something in it we will fix this shortly firstlet' look at how the program does what it does starting at the bottomwe have variable player that keeps track of whose turn it is above that we create the boardwhich consists of nine buttons stored in two-dimensional list we use the lambda trick to pass the row and column of the clicked button to the callback function in the callback function we write an or an into the button that was clicked and change the value of the global variable player
9,304
gui programming with tkinter correcting the problems to correct the problem about being able to change cell that already has something in itwe need to have way of knowing which cells have 'swhich have 'sand which are empty one way is to use button method to ask the button what its text is another waywhich we will do here is to create new two-dimensional listwhich we will call statesthat will keep track of things here is the code from tkinter import def callback( , )global player if player =' and states[ ][ = [ ][cconfigure(text' 'states[ ][ ' player ' if player =' and states[ ][ = [ ][cconfigure(text' 'states[ ][ ' player ' root tk(states [[ , , ][ , , ][ , , ] [[ , , ][ , , ][ , , ]for in range( )for in range( ) [ ][jbutton(font='verdana ' )width= bg'yellow 'command lambda = , =jcallback( , ) [ ][jgrid(row icolumn
9,305
player ' mainloop(we have not added much to the program most of the new action happens in the callback function every time someone clicks on cellwe first check to see if it is empty (that the corresponding index in states is )and if it iswe display an or on the screen and record the new value in states many games have variable like states that keeps track of what is on the board checking for winner we have winner when there are three ' or three ' in roweither verticallyhorizontallyor diagonally to check if there are three in row across the top rowwe can use the following if statementif states[ ][ ]==states[ ][ ]==states[ ][ ]!= stop_game=true [ ][ configure(bg'grey ' [ ][ configure(bg'grey ' [ ][ configure(bg'grey 'this checks to see if each of the cells has the same nonzero entry we are using the shortcut from section here in the if statement there are more verbose if statements that would work if we do find winnerwe highlight the winning cells and then set global variable stop_game equal to true this variable will be used in the callback function whenever the variable is true we should not allow any moves to take place nextto check if there are three in row across the middle rowchange the first coordinate from to in all three referencesand to check if there are three in row across the bottomchange the ' to ' since we will have three very similar if statements that only differ in one locationa for loop can be used to keep the code shortfor in range( )if states[ ][ ]==states[ ][ ]==states[ ][ ]!= [ ][ configure(bg'grey ' [ ][ configure(bg'grey ' [ ][ configure(bg'grey 'stop_game true nextchecking for vertical winners is pretty much the same except we vary the second coordinate instead of the first finallywe have two further if statements to take care of the diagonals the full program is at the end of this we have also added few color options to the configure statements to make the game look little nicer further improvements from here it would be easy to add restart button the callback function for that variable should set stop_game back to falseit should set states back to all zeroesand it should configure all the buttons back to text='and bg='yellowto add computer player would also not be too difficultif you don' mind it being simple com
9,306
gui programming with tkinter puter player that moves randomly that would take about lines of code to make an intelligent computer player is not too difficult such computer player should look for two ' or ' in row in order to try to win or blockas well avoid getting put into no-win situation from tkinter import def callback( , )global player if player =' and states[ ][ = and stop_game==falseb[ ][cconfigure(text' 'fg'blue 'bg'white 'states[ ][ ' player ' if player =' and states[ ][ = and stop_game==falseb[ ][cconfigure(text' 'fg'orange 'bg'black 'states[ ][ ' player ' check_for_winner(def check_for_winner()global stop_game for in range( )if states[ ][ ]==states[ ][ ]==states[ ][ ]!= [ ][ configure(bg'grey ' [ ][ configure(bg'grey ' [ ][ configure(bg'grey 'stop_game true for in range( )if states[ ][ ]==states[ ][ ]==states[ ][ ]!= [ ][iconfigure(bg'grey ' [ ][iconfigure(bg'grey ' [ ][iconfigure(bg'grey 'stop_game true if states[ ][ ]==states[ ][ ]==states[ ][ ]!= [ ][ configure(bg'grey ' [ ][ configure(bg'grey ' [ ][ configure(bg'grey 'stop_game true if states[ ][ ]==states[ ][ ]==states[ ][ ]!= [ ][ configure(bg'grey ' [ ][ configure(bg'grey ' [ ][ configure(bg'grey 'stop_game true root tk( [[ , , ][ , , ]
9,307
[ , , ]states [[ , , ][ , , ][ , , ]for in range( )for in range( ) [ ][jbutton(font='verdana ' )width= bg'yellow 'command lambda = , =jcallback( , ) [ ][jgrid(row icolumn jplayer ' stop_game false mainloop(
9,308
gui programming with tkinter
9,309
gui programming ii in this we cover more basic gui concepts frames let' say we want small buttons across the top of the screenand big ok button below themlike belowwe try the following codefrom tkinter import root tk(alphabet 'abcdefghijklmnopqrstuvwxyz buttons [ ]* for in range( )buttons[ibutton(text=alphabet[ ]buttons[igrid(row= column=iok_button button(text'ok 'font='verdana ' )ok_button grid(row= column= mainloop(but we instead get the following unfortunate result
9,310
gui programming ii the problem is with column there are two widgets therethe button and the ok buttonand tkinter will make that column big enough to handle the larger widgetthe ok button one solution to this problem is shown belowok_button grid(row= column= columnspan= another solution to this problem is to use what is called frame the frame' job is to hold other widgets and essentially combine them into one large widget in this casewe will create frame to group all of the letter buttons into one large widget the code is shown belowfrom tkinter import alphabet 'abcdefghijklmnopqrstuvwxyz root tk(button_frame frame(buttons [ ]* for in range( )buttons[ibutton(button_frametext=alphabet[ ]buttons[igrid(row= column=iok_button button(text'ok 'font='verdana ' )button_frame grid(row= column= ok_button grid(row= column= mainloop(to create framewe use frame(and give it name thenfor any widgets we want include in the framewe include the name of the frame as the first argument in the widget' declaration we still have to grid the widgetsbut now the rows and columns will be relative to the frame finallywe have to grid the frame itself colors tkinter defines many common color nameslike 'yellowand 'redit also provides way to get access to millions of more colors we first have to understand how colors are displayed on the screen each color is broken into three components-- reda greenand blue component each component can have value from to with being the full amount of that color equal parts of red and green create shades of yellowequal parts of red and blue create shades of purpleand equal
9,311
parts of blue and green create shades of turquoise equal parts of all three create shades of gray black is when all three components have values of and white is when all three components have values of varying the values of the components can produce up to million colors there are number of resources on the web that allow you to vary the amounts of the components and see what color is produced to use colors in tkinter is easybut with one catch--component values are given in hexadecimal hexadecimal is base number systemwhere the letters - are used to represent the digits through it was widely used in the early days of computingand it is still used here and there here is table comparing the two number bases fe ff because the color component values run from to they will run from to ff in hexadecimaland thus are described by two hex digits typical color in tkinter is specified like this'# ffthe color name is prefaced with pound sign then the first two digits are the red component (in this case which is in decimalthe next two digits specify the green component (here which is in decimal)and the last two digits specify the blue component (here ffwhich is in decimalthis color turns out to be bluish violet here is an example of it in uselabel label(text'hi 'bg'# ff 'if you would rather not bother with hexadecimalyou can use the following function which will convert percentages into the hex string that tkinter uses def color_convert(rgb)return '#{: }{: }{: xformat(int( * ),int( * )int( * )here is an example of it to create background color that has of the red component of green and of blue label label(text'hi 'bg=color_convert( ) images labels and buttons (and other widgetscan display images instead of text to use an image requires little set-up work we first have to create photoimage object and give it name here is an examplecheetah_image photoimage(file'cheetahs gif '
9,312
gui programming ii here are some examples of putting the image into widgetslabel label(image=cheetah_imagebutton button(image=cheetah_imagecommand=cheetah_callback()you can use the configure method to set or change an imagelabel configure(image=cheetah_imagefile types one unfortunate limitation of tkinter is the only common image file type it can use is gif if you would like to use other types of filesone solution is to use the python imaging librarywhich will be covered in section canvases canvas is widget on which you can draw things like linescirclesrectangles you can also draw textimagesand other widgets on it it is very versatile widgetthough we will only describe the basics here creating canvases the following line creates canvas with white background that is pixels in sizecanvas canvas(width= height= bg'white 'rectangles the following code draws red rectangle to the canvascanvas create_rectangle( , , , fill'red 'see the image below on the left the first four arguments specify the coordinates of where to place the rectangle on the canvas the upper left corner of the canvas is the origin( the upper left of the rectangle is at ( )and the lower right is at ( if were to leave off fill='red'the result would be rectangle with black outline ovals and lines drawing ovals and lines is similar the image above on the right is created with the following code
9,313
canvas create_rectangle( , , , canvas create_oval( , , , fill'blue 'canvas create_line( , , , fill'green 'the rectangle is here to show that lines and ovals work similarly to rectangles the first two coordinates are the upper left and the second two are the lower right to get circle with radius and center ( , )we can create the following functiondef create_circle( , , )canvas create_oval( - , - , + , +rimages we can add images to canvas here is an examplecheetah_image photoimage(file'cheetahs gif 'canvas create_image( , image=cheetah_imagethe two coordinates are where the center of the image should be naming thingschanging themmoving themand deleting them we can give names to the things we put on the canvas we can then use the name to refer to the object in case we want to move it or remove it from the canvas here is an example were we create rectanglechange its colormove itand then delete itrect canvas create_rectangle( , , , canvas itemconfigure(rectfill'red 'canvas coords(rect, , , , canvas delete(rectthe coords method is used to move or resize an object and the delete method is used to delete it if you want to delete everything from the canvasuse the followingcanvas delete(all check buttons and radio buttons in the image belowthe top line shows check button and the bottom line shows radio button check buttons the code for the above check button isshow_totals intvar(check checkbutton(text'show totals 'var=show_totals
9,314
gui programming ii the one thing to note here is that we have to tie the check button to variableand it can' be just any variableit has to be special kind of tkinter variablecalled an intvar this variableshow_totalswill be when the check button is unchecked and when it is checked to access the value of the variableyou need to use its get methodlike thisshow_totals get(you can also set the value of the variable using its set method this will automatically check or uncheck the check button on the screen for instanceif you want the above check button checked at the start of the programdo the followingshow_totals intvar(show_totals set( check checkbutton(text'show totals 'var=show_totalsradio buttons the section isradio buttons work similarly the code for the radio buttons shown at the start of color intvar(redbutton radiobutton(text'red 'var=colorvalue= greenbutton radiobutton(text'green 'var=colorvalue= bluebutton radiobutton(text'blue 'var=colorvalue= the value of the intvar object color will be or depending on whether the leftmiddleor right button is selected these values are controlled by the value optionspecified when we create the radio buttons commands both check buttons and radio buttons have command optionwhere you can set callback function to run whenever the button is selected or unselected text widget the text widget is biggermore powerful version of the entry widget here is an example of creating onetextbox text(font='verdana ' )height= width= the widget will be characters wide and rows tall you can still type past the sixth rowthe widget will just display only six rows at timeand you can use the arrow keys to scroll if you want scrollbar associated with the text box you can use the scrolledtext widget other than the scrollbarscrolledtext works more or less the same as text an example is of what it looks like is shown below to use the scrolledtext widgetyou will need the following importfrom tkinter scrolledtext import scrolledtext
9,315
here are few common commandsstatement description textbox get( ,endreturns the contents of the text box textbox delete( ,enddeletes everything in the text box textbox insert(end,'hello'inserts text at the end of the text box one nice option when declaring the text widget is undo=truewhich allows ctrl+ and ctrl+ to undo and redo edits there are ton of other things you can do with the text widget it is almost like miniature word processor scale widget scale is widget that you can slide back and forth to select different values an example is shown belowfollowed by the code that creates it scale scale(from_= to_= length= orient'horizontal 'here are some of the useful options of the scale widgetoption description from_ minimum value possible by dragging the scale to_ maximum value possible by dragging the scale length how many pixels long the scale is label specify label for the scale showvalue='nogets rid of the number that displays above the scale tickinterval= displays tickmarks at every unit ( can be changedthere are several ways for your program to interact with the scale one way is to link it with an intvar just like with check buttons and radio buttonsusing the variable option another option is to use the scale' get and set methods third way is to use the command optionwhich
9,316
gui programming ii works just like with buttons gui events often we will want our programs to do something if the user presses certain keydrags something on canvasuses the mouse wheeletc these things are called events simple example the first gui program we looked at back in section was simple temperature converter anytime we wanted to convert temperature we would type in the temperature in the entry box and click the calculate button it would be nice if the user could just press the enter key after they type the temperature instead of having to click to calculate button we can accomplish this by adding one line to the programentry bind'lambda dummy= :calculate()this line should go right after you declare the entry box what it does is it takes the event that the enter (returnkey is pressed and binds it to the calculate function wellsort of the function you bind the event to is supposed to be able to receive copy of an event objectbut the calculate function that we had previously written takes no arguments rather than rewrite the functionthe line above uses lambda trick to essentially throw away the event object common events here is list of some common eventsevent description the left mouse button is clicked the left mouse button is double-clicked the left mouse button is released click-and-drag with the left mouse button the mouse wheel is moved the mouse is moved the mouse is now over the widget the mouse has now left the widget key is pressed the key name key is pressed for all of the mouse button examplesthe number can be replaced with other numbers button is the middle button and button is the right button the most useful attributes in the event object are
9,317
attribute description keysym the name of the key that was pressed xy the coordinates of the mouse pointer delta the value of the mouse wheel key events for key eventsyou can either have specific callbacks for different keys or catch all keypresses and deal with them in the same callback here is an example of the latterfrom tkinter import def callback(event)print(event keysymroot tk(root bind'callbackmainloop(the above program prints out the names of the keys that were pressed you can use those names in if statements to handle several different keypresses in the callback functionlike belowif event keysym ='percent 'percent (shift+ was presseddo something about it elif event keysym =' 'lowercase was presseddo something about it use the single callback method if you are catching lot of keypresses and are doing something similar with all of them on the other handif you just want to catch couple of specific keypresses or if certain keys have very long and specific callbacksyou can catch keypresses separately like belowfrom tkinter import def callback (event)print'you pressed the enter key 'def callback (event)print'you pressed the up arrow 'root tk(root bind'callback root bind'callback mainloop(the key names are the same as the names stored in the keysym attribute you can use the program from earlier in this section to find the names of all the keys here are the names for few common keys
9,318
gui programming ii tkinter name common name enter key tab key spacebar page uppage down arrow keys homeend insertdelete caps locknumber lock left and right control keys left and right alt keys left and right shift keys most printable keys can be captured with their nameslike belowroot bind' 'callbackroot bind' 'callbackroot bind''callbackthe exceptions are the spacebar (and the less than sign (you can also catch key combinationssuch as or note these examples all bind keypresses to rootwhich is our name for the main window you can also bind keypresses to specific widgets for instanceif you only want the left arrow key to work on canvas called canvasyou could use the followingcanvas bind(callbackone trick herethoughis that the canvas won' recognize the keypress unless it has the gui' focus this can be done as belowcanvas focus_set( event examples example here is an example where the user can move rectangle with the left or right arrow keys from tkinter import def callback(event)global move if event keysym='right '
9,319
move + elif event keysym='left 'move -= canvas coords(rect, +move, , +move, root tk(root bind'callbackcanvas canvas(width= ,height= canvas grid(row= ,column= rect canvas create_rectangle( , , , ,fill'blue 'move mainloop(example here is an example program demonstrating mouse events the program starts by drawing rectangle to the screen the user can do the followingdrag the rectangle with the mouse (resize the rectangle with the mouse wheel (whenever the user left-clicksthe rectangle will change colors (anytime the mouse is movedthe current coordinates of the mouse are displayed in label (here is the code for the programfrom tkinter import def mouse_motion_event(event)label configure(text'({}{}format(event xevent )def wheel_event(event)global if event delta> diff elif event delta< diff - +=diff -=diff +=diff -=diff canvas coords(rect, , , , def _event(event)global color if not _dragcolor 'red if color='blue else 'blue canvas itemconfigure(rectfill=color
9,320
gui programming ii def _motion_event(event)global _dragx mouse_xmouse_y event event if not _dragmouse_x mouse_y _drag true return +=( -mouse_xx +=( -mouse_xy +=( -mouse_yy +=( -mouse_ycanvas coords(rect, , , , mouse_x mouse_y def _release_event(event)global _drag _drag false root=tk(label label(canvas canvas(width= height= canvas bind'mouse_motion_eventcanvas bind' _eventcanvas bind' _motion_eventcanvas bind' _release_eventcanvas bind'wheel_eventcanvas focus_set(canvas grid(row= column= label grid(row= column= mouse_x mouse_y _drag false color 'blue rect canvas create_rectangle( , , , ,fill=colormainloop(
9,321
here are few notes about how the program works firstevery time the mouse is moved over the canvasthe mouse_motion_event function is called this function prints the mouse' current coordinates which are contained in the event attributes and the wheel_event function is called whenever the user uses the mouse (scrollingwheel the event attribute delta contains information about how quickly and in what direction the wheel was moved we just stretch or shrink the rectangle based on whether the wheel was moved forward or backward the _event function is called whenever the user presses the left mouse button the function changes the color of the rectangle whenever the rectangle is clicked there is global variable here called _drag that is important it is set to true whenever the user is dragging the rectangle when dragging is going onthe left mouse button is down and the _event function is continuously being called we don' want to keep changing the color of the rectangle in that casehence the if statement the dragging is accomplished mostly in the _motion_event functionwhich is called whenever the left mouse button is down and the mouse is being moved it uses global variables that keep track of what the mouse' position was the last time the function was calledand then moves the rectangle according to the difference between the new and old position when the dragging is downthe left mouse button will be released when that happensthe _release_event function is calledand we set the global _drag variable accordingly the focus_set method is needed because the canvas will not recognize the mouse wheel events unless the focus is on the canvas one problem with this program is that the user can modify the rectangle by clicking anywhere on the canvasnot just on rectangle itself if we only want the changes to happen when the mouse is over the rectanglewe could specifically bind the rectangle instead of the whole canvaslike belowcanvas tag_bind(rect' _motion_event
9,322
gui programming ii finallythe use of global variables here is little messy if this were part of larger projectit might make sense to wrap all of this up into class
9,323
gui programming iii this contains few more gui odds and ends title bar the gui window that tkinter creates says tk by default here is how to change itroot title'your title ' disabling things sometimes you want to disable button so it can' be clicked buttons have an attribute state that allows you to disable the widget use state=disabled to disable the button and state=normal to enable it here is an example that creates button that starts out disabled and then enables itbutton button(text'hi 'state=disabledcommand=functionbutton configure(state=normalyou can use the state attribute to disable many other types of widgetstoo getting the state of widget sometimesyou need to know things about widgetlike exactly what text is in it or what its background color is the cget method is used for this for examplethe following gets the text of label called labellabel cget'text '
9,324
gui programming iii this can be used with buttonscanvasesetc and it can be used with any of their propertieslike bgfgstateetc as shortcuttkinter overrides the [operatorsso that label['text'accomplishes the same thing as the example above message boxes message boxes are windows that pop up to ask you question or say something and then go away to use themwe need an import statementfrom tkinter messagebox import there are variety of different types of message boxes for each of them you can specify the message the user will see as well as the title of the message box here are three types of message boxesfollowed by the code that generates themshowinfo(title'message for you 'message'hi there'askquestion(title'quit'message'do you really want to quit'showwarning(title'warning 'message'unsupported format 'below is list of all the types of message boxes each displays message in its own way message box special properties showinfo ok button askokcancel ok and cancel buttons askquestion yes and no buttons askretrycancel retry and cancel buttons askyesnocancel yesnoand cancel buttons showerror an error icon and an ok button showwarning warning icon and an ok button each of these functions returns value indicating what the user clicked see the next section for simple example of using the return value here is table of the return values
9,325
function return value (based on what user clicksshowinfo always returns 'okaskokcancel ok--true askquestion yes--'yesno--'noaskretrycancel retry--true cancel or window closed--false askyesnocancel yes--true showerror always returns 'okshowwarning always returns 'okcancel or window closed--false no--false anything else--none destroying things to get rid of widgetuse its destroy method for instanceto get rid of button called buttondo the followingbutton destroy(to get rid of the entire gui windowuse the followingroot destroy(stopping window from being closed when your user tries to close the main windowyou may want to do somethinglike ask them if they really want to quit here is way to do thatfrom tkinter import from tkinter messagebox import askquestion def quitter_function()answer askquestion(title'quit'message'really quit'if answer='yes 'root destroy(root tk(root protocol'wm_delete_window 'quitter_functionmainloop(the key is the following linewhich cause quitter_function to be called whenever the user tries to close the window root protocol'wm_delete_window 'quitter_function updating tkinter updates the screen every so oftenbut sometimes that is not often enough for instancein function triggered by button presstkinter will not update the screen until the function is done
9,326
gui programming iii ifin that functionyou want to change something on the screenpause for short whileand then change something elseyou will need to tell tkinter to update the screen before the pause to do thatjust use thisroot update(if you only want to update certain widgetand nothing elseyou can use the update method of that widget for examplecanvas update( related thing that is occasionally useful is to have something happen after scheduled time interval for instanceyou might have timer in your program for thisyou can use the after method its first argument is the time in milliseconds to wait before updating and the second argument is the function to call when the time is right here is an example that implements timerfrom time import time from tkinter import def update_timer()time_left int( (time()-start)minutes time_left / seconds time_left time_label configure(text'{}:{: dformat(minutesseconds)root after( update_timerroot tk(time_label label(time_label grid(row= column= start time(update_timer(mainloop(this example uses the time modulewhich is covered in section dialogs many programs have dialog boxes that allow the user to pick file to open or to save file to use them in tkinterwe need the following import statementfrom tkinter filedialog import tkinter dialogs usually look like the ones that are native to the operating system
9,327
here are the most useful dialogsdialog description askopenfilename opens typical file chooser dialog askopenfilenames like previousbut user can pick more than one file asksaveasfilename opens typical file save dialog askdirectory opens directory chooser dialog the return value of askopenfilename and asksaveasfilename is the name of the file selected there is no return value if the user does not pick value the return value of askopenfilenames is list of fileswhich is empty if no files are selected the askdirectory function returns the name of the directory chosen there are some options you can pass to these functions you can set initialdir to the directory you want the dialog to start in you can also specify the file types here is an examplefilename=askopenfilename(initialdir' :\\python \'filetypes=['image files 'jpg png gif ')'all files ''')] short example here is an example that opens file dialog that allows you to select text file the program then displays the contents of the file in textbox from tkinter import from tkinter filedialog import from tkinter scrolledtext import scrolledtext root tk(textbox scrolledtext(textbox grid(filename=askopenfilename(initialdir' :\\python \'filetypes=['text files 'txt ')
9,328
gui programming iii 'all files ''')] open(filenameread(textbox insert( smainloop( menu bars we can create menu barlike the one belowacross the top of window here is an example that uses some of the dialogs from the previous sectionfrom tkinter import from tkinter filedialog import def open_callback()filename askopenfilename(add code here to do something with filename def saveas_callback()filename asksaveasfilename(add code here to do something with filename root tk(menu menu(root config(menu=menufile_menu menu(menutearoff= file_menu add_command(label'open 'command=open_callbackfile_menu add_command(label'save as 'command=saveas_callbackfile_menu add_separator(file_menu add_command(label'exit 'command=root destroymenu add_cascade(label'file 'menu=file_menumainloop( new windows creating new window is easy use the toplevel functionwindow toplevel(
9,329
you can add widgets to the new window the first argument when you create the widget needs to be the name of the windowlike below new_window toplevel(label label(new_windowtext'hi 'label grid(row= column= pack there is an alternative to grid called pack it is not as versatile as gridbut there are some places where it is useful it uses an argument called sidewhich allows you to specify four locations for your widgetstopbottomleftand right there are two useful optional argumentsfill and expand here is an example button =button(text'hi 'button pack(side=topfill=xbutton =button(text'hi 'button pack(side=bottomthe fill option causes the widget to fill up the available space given to it it can be either xy or both the expand option is used to allow the widget to expand when its window is resized to enable ituse expand=yes note you can use pack for some framesand grid for othersjust don' mix pack and grid within the same frameor tkinter won' know quite what to do stringvar in section we saw how to tie tkinter variablecalled an intvarto check button or radio button tkinter has another type of variable called stringvar that holds strings this type of variable can be used to change the text in label or button or in some other widgets we already know how to change text using the configure methodand stringvar provides another way to do it to tie widget to stringvaruse the textvariable option of the widget stringvar has get and set methodsjust like an intvarand whenever you set the variableany widgets that are tied to it are automatically updated
9,330
gui programming iii here is simple example that ties two labels to the same stringvar there is also button that when clicked will alternate the value of the stringvar (and hence the text in the labelsfrom tkinter import def callback()global count set'goodbye if count% == else 'hello 'count += root tk(count stringvar( set'hello 'label label(textvariable swidth= label label(textvariable swidth= button button(text 'click me 'command callbacklabel grid(row= column= label grid(row= column= button grid(row= column= mainloop( more with guis we have left out quite lot about tkinter see lundh' introduction to tkinter [ for more tkinter is versatile and simple to work withbut if you need something more powerfulthere are other third-party guis for python
9,331
further graphical programming python vs python as of this writingthe most recent version of python is and all the code in this book is designed to run in python the tricky thing is that as of version python broke compatibility with older versions of python code written in those older versions will not always work in python the problem with this is there were number of useful libraries written for python thatas of this writinghave not yet been ported to python we want to use these librariesso we will have to learn little about python fortunatelythere are only few big differences that we have to worry about division the division operator/in python when used with integersbehaves like /for instance / in python evaluates to whereas / in python evaluates to this is the way the division operator behaves in number of other programming languages in python the decision was made to make the division operator behave the way we are used from math in python if you want to get by dividing and you need to do at least one of the arguments has to be float in order for the result to be float if you are dividing two variablesthen instead of /yyou may need to do /float(yprint the print function in python was actually the print statement in python so in python you would write print 'hello without any parentheses this code will no longer work in python because the print statement is now the print functionand functions need parentheses alsothe current print function has those useful optional argumentssep and endthat are not available in python
9,332
further graphical programming input the python equivalent of the input function is raw_input range the range function can be inefficient with very large ranges in python the reason is that in python if you use range( )python will create list of million numbers the range statement in python is more efficient and instead of generating all million things at onceit only generates the numbers as it needs them the python function that acts like the python range is xrange string formatting string formatting in python is little different than in python when using the formatting codes inside curly bracesin python you need to specify an argument number compare the examples belowpython ' ={ : }, ={ : }, ={ : }format( , ,zpython ' ={: }, ={: } ={: }format( , ,zas of python specifying the argument numbers was made optional there is also an older style of formatting that you may see from time to time that uses the operator an example is shown below along with the corresponding new style python ' =% dy=% fz=% ( , ,zpython ' ={: }, ={: }, ={: }format( , ,zmodule names some modules were renamed and reorganized here are few tkinter name changespython python tkinter tkinter scrolledtext tkinter scrolledtext tkmessagebox tkinter messagebox tkfiledialog tkinter filedialog there are number of other modules we'll see later that were renamedmostly just changed to lowercase for instancequeue in python is now queue in python dictionary comprehensions dictionary comprehensions are not present in python other changes there are quite few other changes in the languagebut most of them are with features more advanced than we consider here
9,333
importing future behavior in python the following import allows us to use python ' division behavior from __future__ import division there are many other things you can import from the future the python imaging library the python imaging library (pilcontains useful tools for working with images as of this writingthe pil is only available for python or earlier the pil is not part of the standard python distributionso you'll have to download and install it separately it' easy to installthough pil hasn' been maintained since but there is project called pillow that it nearly compatible with pil and works in python and later we will cover just few features of the pil here good reference is the python imaging library handbook using images other than gifs with tkinter tkinteras we've seencan' use jpegs and pngs but it can if we use it in conjunction with the pil here is simple examplefrom tkinter import from pil import imageimagetk root tk(cheetah_image imagetk photoimage(image open'cheetah jpg ')button button(image=cheetah_imagebutton grid(row= column= mainloop(the first line imports tkinter remember that in python it' an uppercase tkinter the next line imports few things from the pil nextwhere we would have used tkinter' photoimage to load an imagewe instead use combination of two pil functions we can then use the image like normal in our widgets images pil is the python imaging libraryand so it contains lot of facilities for working with images we will just show simple example here the program below displays photo on canvas and when the user clicks buttonthe image is converted to grayscale from tkinter import from pil import imageimagetk def change()global imagephoto pix image load(
9,334
further graphical programming for in range(photo width())for in range(photo height())red,green,blue pix[ ,javg (red+green+blue)// pix[ , (avgavgavgphoto=imagetk photoimage(imagecanvas create_image( , ,image=photo,anchor=nwdef load_file(filename)global imagephoto image=image open(filenameconvert'rgb 'photo=imagetk photoimage(imagecanvas configure(width=photo width()height=photo height()canvas create_image( , ,image=photo,anchor=nwroot title(filenameroot tk(button button(text'change 'font='verdana ' )command=changecanvas canvas(canvas grid(row= button grid(row= load_file'pic jpg 'mainloop(let' first look at the load_file function many of the image utilities are in the image module we give nameimageto the object created by the image open statement we also use the convert method to convert the image into rgb (red-green-blueformat we will see why in minute the next line creates an imagetk object called photo that gets drawn to the tkinter canvas the photo object has methods that allow us to get its width and height so we can size the canvas appropriately now look at the change function the image object has method called load that gives access to the individual pixels that make up the image this returns two-dimensional array of rgb values for instanceif the pixel in the upper left corner of the image is pure whitethen pix[ , will be ( , , if the next pixel to the right is pure blackpix[ , will be ( , , to convert the image to grayscalefor each pixel we take the average of its redgreenand blue componentsand reset the redgreenand blue components to all equal that average remember that if the redgreenand blue are all the samethen the color is shade of gray after modifying all the pixelswe create new imagetk object from the modified pixel data and display it on the canvas you can have lot of fun with this try modifying the change function for instanceif we use the following line in the change functionwe get an effect that looks like photo negativepix[ , ( -red -green -bluetry seeing what interesting effects you can come up with notethoughthat this way of manipulating images is the slowmanual way pil has number of much faster functions for modifying images you can very easily change the brightnesshueand contrast of imagesresize themrotate themand much more see the pil reference materials for more on this
9,335
putdata if you are interested drawing mathematical objects like fractalsplotting points pixelby-pixel can be very slow in python one way to speed things up is to use the putdata method the way it works is you supply it with list of rgb pixel valuesand it will copy it into your image here is program that plots grid of random colors from random import randint from tkinter import from pil import imageimagetk root tk(canvas canvas(width= height= canvas grid(image=image new(mode'rgb ',size=( , ) [(randint( , )randint( , )randint( , )for in range( for in range( )image putdata(lphoto=imagetk photoimage(imagecanvas create_image( , ,image=photo,anchor=nwmainloop(figure (leftputdata example (rightimagedraw example imagedraw the imagedraw module gives another way to draw onto images it can be used to draw rectanglescirclespointsand morejust like tkinter canvasesbut it is faster here is short example that fills the image with dark blue color and then randomly distributed yellow points from random import randint from tkinter import
9,336
further graphical programming from pil import imageimagetkimagedraw root tk(canvas canvas(width= height= canvas grid(image=image new(mode'rgb ',size=( , )draw imagedraw draw(imagedraw rectangle([( , ),( )],fill'# ' [(randint( , )randint( )for in range( )draw point(lfill'yellow 'photo=imagetk photoimage(imagecanvas create_image( , ,image=photo,anchor=nwmainloop(to use imagedrawwe have to first create an imagedraw object and tie it to the image object the draw rectangle method works similarly to the create_rectangle method of canvasesexcept for few differences with parentheses the draw point method is used to plot individual pixels nice feature of it is we can pass list of points instead of having to plot each thing in the list separately passing list is also much faster pygame pygame is library for creating two-dimensional games in python it can be used to can make games at the level of old arcade or nintendo games it can be downloaded and easily installed from www pygame org there are number of tutorials there to help you get started don' know whole lot about pygameso won' cover it herethough perhaps in later edition will
9,337
intermediate topics
9,338
miscellaneous topics iii in this we examine variety of useful topics mutability and references if is list and is stringthen [ gives the first element of the list and [ the first element of the string if we want to change the first element of the list to [ ]= will do it but we cannot change string this way the reason has to do with how python treats lists and strings lists (and dictionariesare said to be mutablewhich means their contents can change stringson the other handare immutablewhich means they cannot be changed the reason strings are immutable is partly for performance (immutable objects are fasterand partly because strings are thought of fundamental in the same way that numbers are it makes some other aspects of the language easier as well making copies another place that lists and strings differ is when we try to make copies consider the following codes 'hello copy '!!print' is now'ss is nowhello!!copy'copycopyhello in the code above we make copy of and then change everything works as we would intuitively expect now look at similar code with listsl [ , , copy
9,339
miscellaneous topics iii [ ]= print' is now'lcopy'copyl is now[ copy[ we can see that the list code did not work as we might have expected when we changed lthe copy got changed as well as mentioned in the proper way to make copy of is copy= [:the key to understanding these examples is references references everything in python is an object this includes numbersstringsand lists when we do simple variable assignmentlike = what actually happens is python creates an integer object with the value and the variable acts as reference to that object it' not that the value is stored in memory location named xbut rather that is stored somewhere in memoryand points to that location if we come along and declare = then also points to that same memory location on the other handif we then come along and say = what happens is we create new integer object with value somewhere in memory and now points at that the still exists in memory where it was and it will stay there at least until there is nothing left pointing at itat which point its memory location will be free to use for something else all objects are treated the same way when we set ='hello'the string object hello is somewhere in memory and is reference to it when we then say copy=xwe are actually saying that copy is another reference to 'helloif we then do = +'!!!'what happens is new object 'hello!!!is created and because we assigned to its is now reference to that new object'hello!!!remember that strings are immutableso there is no changing 'hellointo something ratherpython creates new object and points the variable to it when we set =[ , , ]we create list object [ , , and referencelto it when we say copy=lwe are making another reference to the object [ , , when we do [ ]= because lists are mutablethe list [ , , is changedin placeto [ , , no new object is created the list [ , , is now goneand since copy is still pointing to the same locationit' value is [ , , on the other handif we instead use copy= [:]we are actually creating new list object somewhere else in memory so that there are two copies of [ , , in memory then when we do [ ]= we are only changing the thing that points toand copy still points to [ , , just one further note to drive the point home if we set = and then set = we are first creating an integer object and pointing to it when we then set = we are creating new integer object and pointing to it the net effect is that it seems like the "valueof is changingbut what is in fact changing is what is pointing to garbage collection internally python maintains count of how many references there are to each object when the reference count of an object drops to then the object is no longer neededand the memory it had been using becomes available again
9,340
tuples tuple is essentially an immutable list below is list with three elements and tuple with three elementsl [ , , ( , , tuples are enclosed in parenthesesthough the parentheses are actually optional indexing and slicing work the same as with lists as with listsyou can get the length of the tuple by using the len functionandlike liststuples have count and index methods howeversince tuple is immutableit does not have any of the other methods that lists havelike sort or reverseas those change the list we have seen tuples in few places already for instancefonts in tkinter are specified as pairslike ('verdana', )and sometimes as triples the dictionary method items returns list of tuples alsowhen we use the following shortcut for exchanging the value of two or more variableswe are actually using tuplesa, , one reason why there are both lists and tuples is that in some situationsyou might want an immutable type of list for instancelists cannot serve as keys in dictionaries because the values of lists can change and it would be nightmare for python dictionaries to have to keep track of tupleshowevercan serve as keys in dictionaries here is an example assigning grades to teams of studentsgrades {'john ''ann ') 'mike ''tazz ') alsoin situations where speed really matterstuples are generally faster than lists the flexibility of lists comes with corresponding cost in speed tuple to convert an object into tupleuse tuple the following example converts list and string into tuplest tuple([ , , ] tuple'abcde 'note the empty tuple is (the way to get tuple with one element is like this( ,something like ( will not work because that just evaluates to as in an ordinary calculation for instancein the expression +( * )we don' want the ( * to be tuplewe want it to evaluate to number sets python has data type called set sets work like mathematical sets they are lot like lists with no repeats sets are denoted by curly braceslike below
9,341
miscellaneous topics iii { , , , , recall that curly braces are also used to denote dictionariesand {is the empty dictionary to get the empty setuse the set function with no argumentslike thiss set(this set function can also be used to convert things to sets here are two examplesset([ , , , , , , , , ]set'this is test '{ 'aeihst notice that python will store the data in set in whatever order it wants tonot necessarily the order you specify it' the data in the set that mattersnot the order of the data this means that indexing has no meaning for sets you can' do [ ]for instance working with sets there are few operators that work with sets operator description example union { , , { , { , , , intersection { , , { , { difference { , , { , { , symmetric difference { , , { , { , , in is an element of in { , , true the symmetric difference of two sets gives the elements that are in one or the other setbut not both here are some useful methodsmethod description add(xadd to the set remove(xremove from the set issubset(areturns true if and false otherwise issuperset(areturns true if and false otherwise finallywe can do set comprehensions just like list comprehensionss { ** for in range( ){ set comprehensions are not present in python exampleremoving repeated elements from lists we can use the fact that set can have no repeats to remove all repeats from list here is an example
9,342
[ , , , , , , , , list(set( )after thisl will equal [ , , , , examplewordplay here is an example of an if statement that uses set to see if every letter in word is either an abcdor eif set(wordcontainedin'abcde ') unicode it used to be computers could only display different characterscalled ascii characters in this systemcharacters are allotted one byte of memory eachwhich gives possible characterseach with corresponding numerical value characters through include various control charactersincluding '\nand '\tafter that came some special symbolsthen numberscapital letterslowercase lettersand few more symbols beyond that are variety of other symbolsincluding some international characters however characters is not nearly enough to represent all of the symbols used throughout the alphabets of the world the new standard is unicodewhich uses more than one byte to store character data unicode currently supports over , characters "standardisn' quite the right word hereas there are actually several standards in useand this can cause some trouble if you need to work with unicode datado some research into it first to learn about all the craziness in unicodecharacters still have numerical equivalents if you would like to go back and forth between character and its numerical equivalentuse the chr and ord built-in functions for exampleuse ord(' 'to get the numerical value of ' 'and use chr( to get the character with numerical value here is short example that prints out the first unicode characters print'join([chr(ifor in range( )])python supports unicodeboth in strings and in the names of variablesfunctionsetc there are some differences between python and python in support for unicode
9,343
miscellaneous topics iii sorted first definitionan iterable is an object that allows you to loop through its contents iterables include liststuplesstringsand dictionaries there are number of python methods that work on any iterable the sorted function is built-in function that can be used to sort an iterable as first examplewe can use it to sort list say =[ , , the following sets to [ , , sorted(lthe difference between sorted and sort is that sort(changes the original list lbut sorted(ldoes not the sorted function can be used on other iterables the result is sorted list for instancesorted('xyzab'returns the list [' ',' ',' ',' ',' 'if we really want the result to be stringwe can use the join methods 'join(sorted'xyzab ')this sets to 'abxyzusing sorted on dictionary sorts the keys if-else operator this is convenient operator that can be used to combine an if/else statement into single line here is an examplex ' if == else ' this is equivalent to if == ' elsex' here is another example along with two sample outputsprint'he scored 'scorepoint '' if score> else 'sep''he scored points he scored point continue the continue statement is cousin of the break statement for loops when continue statement is encountered in for loopthe program ignores all the code in the loop beyond the continue
9,344
statement and jumps back up to the start of the loopadvancing the loop counter as necessary here is an example the code on the right accomplishes the same thing as the code on the left for in lif not in foundcount+= if [ ]=' 'count += for in lif in foundcontinue count+= if [ ]=' 'count += the continue statement is something you can certainly do withoutbut you may see it from time to time and it occasionally can make for simpler code eval and exec the eval and exec functions allow program to execute python code while the program is running the eval function is used for simple expressionswhile exec can execute arbitrarily long blocks of code eval we have seen eval many times before with input statements one nice thing about using eval with an input statement is that the user need not just enter number they can enter an expression and python will compute it for instancesay we have the followingnum eval(input'enter number')the user can enter *( + and python will compute that expression you can even use variables in the expression here is an example of eval in action def countif(lcondition)return len([ for in if eval(condition)]this behaves like spreadsheet countif function it counts how many items in list satisfy certain condition what eval does for us here is allows the condition to be specified by the user as string for instancecountif( ,' > 'will return how many items in are greater than here is another common spreadsheet functiondef sumif(lcondition)return sum([ for in if eval(condition)]exec plethe exec function takes string consisting of python code and executes it here is an exams """ = for in range( )print( * )""exec(
9,345
miscellaneous topics iii one nice use of the exec function is to let program' user define math functions to use while the program is running here is the code to do thats input'enter function'exec'def ( )return si have used this code in graph plotting program that allows users to enter equations to be graphedand have used it in program where the user can enter function and the program will numerically approximate its roots you can use exec to have your program generate all sorts of python code while it is running this allows your program to essentially modify itself while it is running note in python exec is statementnot functionso you may see it used without parentheses in older code security issue the eval and exec functions can be dangerous there is always the chance that your users might input some code that could do something dangerous to the machine they could also use it to inspect the values of your variables (which could be bad iffor some reasonyou were storing passwords in variablesoyou will want to be careful about using these functions in code where security is important one option for getting input without eval is to do something like thisnum int(input'enter number')this assumes num is an integer use float or list or whatever is appropriate to the data you are expecting enumerate and zip the built-in enumerate function takes an iterable and returns new iterable consisting of pairs ( ,xwhere is an index and is the corresponding element from the iterable for examples 'abcde for ( ,xin enumerate( )print( + the object returned is something that is like list of pairsbut not exactly the following will give list of pairslist(enumerate( )
9,346
the for loop above is equivalent to the followingfor in range(len( ))print( + [ ]the enumerate code can be shorter or clearer in some situations here is an example that returns list of the indices of all the ones in string[ for ( ,cin enumerate(sif =' 'zip the zip function takes two iterables and "zipsthem up into single iterable that contains pairs ( , )where is from the first iterableand is from the second here is an examples 'abc [ zip( ,lprint(list( )[(' ', ])(' ', )(' ', )just like with enumeratethe result of zip is not quite listbut if we do list(zip( , ))we can get list from it here is an example that uses zip to create dictionary from two lists 'one ''two ''three ' [ dict(zip( , ){'three' 'two' 'one' this technique can be used to create dictionary while your program is running copy the copy module has couple of useful methodscopy and deepcopy the copy method can be usedfor instanceto make copy of an object from user-defined class as an examplesuppose we have class called users and we want to make copy of specific user we could do the followingfrom copy import copy u_copy copy(ubut the copy method has certain limitationsas do other copying techniqueslike = [:for lists for examplesuppose [ , , ],[ , , ]if we make copy of this by doing = [:]and then set [ ][ ]= this will affect [ ][ as well this is because the copy is only shallow copy--the references to the sublists that make up were copiedinstead of copies of those sublists this sort of thing can be problem anytime we are copying an object that itself consists of other objects
9,347
miscellaneous topics iii the deepcopy method is used in this type of situation to only copy the values and not the references here is how it would workfrom copy import deepcopy deepcopy( more with strings there are few more facts about strings that we haven' yet talked about translate the translate method is used to translate stringscharacter-by-character the translation is done in two steps firstuse maketrans to create special kind of dictionary that defines how things will be translated you specify an ordinary dictionary and it creates new one that is used in the translation then pass that dictionary to the translate method to do the translating here is simple exampled str maketrans(' '' '' '' '}print'abaab translate( )the result is ' here is an example where we use translate to implement simple substitution cipher substitution cipher is simple way to encrypt messagewhere each letter is replaced by different letter for instancemaybe every is replaced by gand every by an xetc here is the codefrom random import shuffle create the key alphabet 'abcdefghijklmnopqrstuvwxyz list(alphabetshuffle(lcreate the encoding and decoding dictionaries encode_dict str maketrans(dict(zip(alphabetl))decode_dict str maketrans(dict(zip(lalphabet))encode and decode 'this is secret 'this is secret translate(encode_dictt translate(decode_dictprint(alphabet'join( )tssep'\ 'abcdefghijklmnopqrstuvwxyz qjdpaztxghuflicornkesyvmwb exgk gk kadnae this is secret the way it works is we first create the encryption keywhich says which letter gets replaced withb gets replaced withetc this is done by shuffling the alphabet we then create translation
9,348
table for both encoding and decodingusing the zip trick of section for creating dictionaries finallywe use the translate method to do the actual substituting partition the partition method is similar to the list split method the difference is illustrated below' partition'' split'(' ''' '[' '' the difference is that the argument to the function is returned as part of the output the partition method also returns tuple instead of list here is an example that calculates the derivative simple monomial entered as string the rule for derivatives is that the derivative of ax is nax - input'enter monomial'coeffpower partition' 'print'{} ^{format(int(coeff)*int(power)int(power)- enter monomial ^ ^ note these methodsand many otherscould be done directly just using the basic tools of the language like for loopsif statementsetc the ideathoughis that those things that are commonly done are made into methods or classes that are part of the standard python distribution this can help you from having to reinvent the wheel and they can also make your programs more reliable and easier to read comparing strings comparison of strings is done alphabetically for examplethe following will print yes if 'that 'this 'print'yes 'beyond thatif the string contains characters other than lettersthe comparison is based off the ord value of the characters miscellaneous tips and tricks here are few useful tips
9,349
miscellaneous topics iii statements on the same line the same line you can write an if statement and the statement that goes with it on if == print'hello 'you can also combine several statements on line if you separate them by semicolons for examplea= = = don' overuse either of theseas they can make your code harder to read sometimesthoughthey can make it easier to read calling multiple methods you can call several methods in rowlike belows open'file txt 'read(upper(this example reads the contents of filethen converts everything to uppercaseand stores the result in againbe careful not to overdo it with too many methods in row or your code may be difficult to read none in addition to intfloatstrlistetc python has data type called none it basically is the python version of nothing it indicates that there is nothing when you might have expected there to be somethingsuch as the return value of function you may see it show up here and there documentation strings when defining functionyou can specify string that contains information about how the function works then anyone who uses the function can use python' help function to get information about your function here an exampledef square( )""returns squared ""return ** help(squarehelp on function square in module __main__square(xreturns squared you can also use documentation strings right after class statement to provide information about your class running your python programs on other computers your python programs can be run on other computers that have python installed macs and linux machines usually have python installedthough the version may not be up to date with the one
9,350
you are usingand those machines may not have additional libraries you are using an option on windows is py exe this is third-party module that converts python programs to executables as of nowit is only available for python it can be little tricky to use here is script that you can use once you have py exe installed import os program_name raw_input'enter name of program'if program_name[- :]!py 'program_name+py with open'temp_py exe py '' 'as fps 'from distutils core import setup\ +"import py exe\nsetup(console=[' +program_name "'])fp write(sos system' :\python \python temp_py exe py py exe 'if everything worksa window should pop up and you'll see bunch of stuff happening quickly the resulting executable file will show up in new subdirectory of the directory your python file is incalled dist there will be few other files in that subdirectory that you will need to include with your executable
9,351
miscellaneous topics iii
9,352
useful modules python comes with hundreds of modules that do all sorts of things there are also many thirdparty modules available for download from the internet this discusses few modules that have found useful importing modules there are couple of different ways to import modules here are several ways to import some functions from the random module from random import randintchoice from random import import random the first way imports just two functions from the module the second way imports every function from the module you should usually avoid doing thisas the module may contain some names that will interfere with your own variable names for instance if your program uses variable called total and you import module that contains function called totalthere can be problems some moduleshoweverlike tkinterare fairly safe to import this way the third way imports an entire module in way that will not interfere with your variable names to use function from the modulepreface it with random followed by dot for instancerandom randint( , changing module names the as keyword can be used to change the name that your program uses to refer to module or things from module here are three examplesimport numpy as np
9,353
useful modules from itertools import combinations_with_replacement as cwr from math import log as ln location usuallyimport statements go at the beginning of the programbut there is no restriction they can go anywhere as long as they come before the code that uses the module getting help to get help on module (say the random moduleat the python shellimport it using the third way above then dir(randomgives list of the functions and variables in the moduleand help(randomwill give you rather long description of what everything does to get help on specific functionlike randinttype help(random randint dates and times the time module has some useful functions for dealing with time sleep the sleep function pauses your program for specified amount of time (in secondsfor instanceto pause your program for seconds or for millisecondsuse the followingsleep( sleep timing things the time function can be used to time things here is an examplefrom time import time start time(do some stuff print'it took 'round(time()-start )'seconds 'for another examplesee section which shows how to put countdown timer into gui the resolution of the time(function is milliseconds on windows and microseconds on linux the above example uses whole seconds if you want millisecond resolutionuse the following print statementprint'{ fseconds format(time()-start)you can use little math on this to get minutes and hours here is an examplet time()-start secs % mins // hours mins// by the waywhen you call time()you get rather strange value like it is the number of seconds elapsed since january
9,354
dates the module datetime allows us to work with dates and times together the following line creates datetime object that contains the current date and timefrom datetime import datetime datetime( , , now(the datetime object has attributes yearmonthdayhourminutesecondand microsecond here is short exampled datetime( , , now(print'{}:{: {}/{}/{format( hour, minute, month, day, year) : the hour is in -hour format to get -hour formatyou can do the followingam_pm 'am if hour< else 'pm print'{}:{}{format( hour% minuteam_pm)an alternative way to display the date and time is to use the strftime method it uses variety of formatting codes that allow you to display the date and timeincluding information about the day of the weekam/pmetc here are some of the formatting codescode description % date and time formatted according to local conventions % % % is the dateand % is the timeboth formatted as with % % day of the month % day of the year % % weekday name (% is the abbreviated weekday name% month ( - % % month name (% is the abbreviated month name% % year (% is -digit% is -digit% % hour (% is -hour% is -hour% am or pm % minute % second here is an exampleprint( strftime'% % ')tuesday here is another exampleprint( strftime'% ')print( strftime'% % on % % ')
9,355
useful modules : : am on february the leading zeros are little annoying you could combine strftime with the first way we learned to get nicer outputprint( strftime'{}% on % {'format( hour% day) am on february you can also create datetime object when doing soyou must specify the yearmonthand day the other attributes are optional here is an exampled datetime( datetime( you can compare datetime objects using the ==and !operators you can also do arithmetic on datetime objectsthough we won' cover it here in factthere is lot more you can do with dates and times another nice module is calendar which you can use to print out calendars and do more sophisticated calculations with dates working with files and directories the os module and the submodule os path contain functions for working with files and directories changing the directory when your program opens filethe file is assumed to be in the same directory as your program itself if notyou have to specify the directorylike belows open' :/users/heinold/desktop/file txt 'read(if you have lot of files that you need to readall in the same directoryyou can use os chdir to change the directory here is an exampleos chdir' :/users/heinold/desktop' open'file txt 'read(getting the current directory the function getcwd returns the path of current directory it will be the directory your program is in or the directory you changed it to with chdir getting the files in directory the function listdir returns list of the entries in directoryincluding all files and subdirectories if you just want the files and not the subdirectories or viceversathe os path module contains the functions isfile and isdir to tell if an entry is file or
9,356
directory here is an example that searches through all the files in directory and prints the names of those files that contain the word 'helloimport os directory ' :/users/heinold/desktopfiles os listdir(directoryfor in filesif os path isfile(directory+ ) open(directory+fread(if 'hello in sprint(fchanging and deleting files here are few useful functions just be careful here function description mkdir create directory rmdir remove directory remove delete file rename rename file the first two functions take directory path as their only argument the remove function takes single file name the first argument of rename is the old name and the second argument is the new name copying files there is no function in the os module to copy files insteaduse the copy function in the shutil module here is an example that takes all the files in directory and makes copy of eachwith each copied file' name starting with copy of import os import shutil directory ' :/users/heinold/desktopfiles os listdir(directoryfor in filesif os path isfile(directory+ )shutil copy(directory+fdirectory'copy of '+fmore with os path the os path module contains several more functions that are helpful for working with files and directories different operating systems have different conventions for how they handle pathsand the functions in os path allow your program to work with different operating systems without having to worry about the specifics of each one here are some examples (on my windows system)print(os path split' :/users/heinold/desktop/file txt ')print(os path basename' :/users/heinold/desktop/file txt ')print(os path dirname' :/users/heinold/desktop/file txt ')
9,357
useful modules print(os path join'directory ''file txt ')(' :/users/heinold/desktop''file txt'file txt :/users/heinold/desktop directory\\file txt note that the standard separator in windows is the backslash the forward slash also works finallytwo other functions you might find helpful are the exists functionwhich tests if file or directory existsand getsizewhich gets the size of file there are many other functions in os path see the python documentation [ for more information os walk the os walk function allows you to scan through directory and all of its subdirectories here is simple example that finds all the python files on my desktop or in subdirectories of my desktopfor (pathdirsfilesin os walk' :/users/heinold/desktop')for filename in filesif filename[- :]=py 'print(filename running and quitting programs running programs there are few different ways for your program to run another program one of them uses the system function in the os module here is an exampleimport os os chdir' :/users/heinold/desktop 'os system'file exe 'the system function can be used to run commands that you can run at command prompt another way to run your programs is to use the execv function quitting your program the sys module has function called exit that can be used to quit your program here is simple exampleimport sys ans input'quit the program'if ans lower(='yes sys exit( zip files zip file is compressed file or directory of files the following code extracts all the files from zip filefilename zipto my desktop
9,358
import zipfile zipfile zipfile'filename zip ' extractall' :/users/heinold/desktop/ getting files from the internet for getting files from the internet there is the urllib module here is simple examplefrom urllib request import urlopen page urlopen' page read(decode(the urlopen function returns an object that is lot like file object in the example abovewe use the read(and decode(methods to read the entire contents of the page into string the string in the example above is filled with the text of an html filewhich is not pretty to read there are modules in python for parsing htmlbut we will not cover them here the code above is useful for downloading ordinary text files of data from the internet for anything more sophisticated than thisconsider using the third party requests library sound an easy way to get some simple sounds in your program is to use the winsound module it only works with windowshowever one function in winsound is beep which can be used to play tone at given frequency for given amount of time here is an example that plays sound of hz for second from winsound import beep beep( , the first argument to beep is the frequency in hertz and the second is the duration in milliseconds another function in winsound is playsoundwhich can be used to play wav files here is an examplefrom winsound import playsound playsound'soundfile wav ''snd_alias 'on the other handif you have pygame installedit is pretty easy to play any type of common sound file this is shown belowand it works on systems other than windowsimport pygame pygame mixer init( ,- , , sound pygame mixer sound'soundfile wav 'sound play(
9,359
useful modules your own modules creating your own modules is easy just write your python code and save it in file you can then import your module using the import statement
9,360
regular expressions the replace method of strings is used to replace all occurrences of one string with anotherand the index method is used to find the first occurrence of substring in string but sometimes you need to do more sophisticated search or replace for exampleyou may need to find all of the occurrences of string instead of just the first one or maybe you want to find all occurrences of two letters followed by number or perhaps you need to replace every 'quthat is at the start of word with 'quthis is what regular expressions are for utilities for working with regular expressions are found in the re module there is some syntax to learn in order to understand regular expressions here is one example to give you an idea of how they workimport re print(re sub( '([lrud])(\ +''**''locations and full ')locations **and **full this example replaces any occurrence of an lruor followed by one or more digits with '*** introduction sub the sub function works as followssub(patternreplacementstringthis searches through string for pattern and replaces anything matching that pattern with the string replacement all of the upcoming examples will be shown with subbut there are other things we can do with regular expressions besides substituting we will get to those after discussing the syntax of regular expressions
9,361
regular expressions raw strings lot of the patterns use backslashes howeverbackslashes in strings are used for escape characterslike the newline\ to get backslash in stringwe need to do \this can quickly clutter up regular expression to avoid thisour patterns will be raw stringswhere backslashes can appear as is and don' do anything special to mark string as raw stringpreface it with an like belows 'this is raw string backslashes do not do anything special syntax basic example we start with regular expression that mimics the replace method of strings here is example of using replace to replace all occurrences of abc with *'abcdef abcxyz replace'abc '''*def *xyz here is the regular expression code that does the same thingre sub( 'abc ''''abcdef abcxyz 'square brackets we can use square brackets to indicate that we only want to match certain letters here is an example where we replace every and with asterisksre sub( '[ad''''abcdef '*bc*ef here is another examplewhere an asterisk replaces all occurrences of an abor that is followed by or re sub( '[abc][ '''' ' we can give ranges of values--for example[ -jfor the letters through here are some further examples of rangesrange description [ -zany capital letter [ - any digit [ -za- - any letter or digit slightly shorter way to match any digit is \dinstead of [ - matching any character use dot to match (almostany character here is an examplere sub( ' '''' axb axxb $ '
9,362
axxb the pattern matches an followed by almost any single character followed by exceptionthe one character not matched by the dot is the newline character if you need that to be matchedtooput ? at the start of your pattern matching multiple copies of something here is an example where we match an followed by one or more 'sre sub( 'ab''''abc abbbbbbc ac* * ac we use the character to indicate that we want to match one or more ' here there are similar things we can use to specify different numbers of ' here for instanceusing in place of will match zero or more ' (this means that ac in the example above would be replaced by * because counts as an followed by zero ' here is table of what you can docode description match or more occurrences match or more occurrences match or occurrence {mmatch exactly occurrences { ,nmatch between and occurrencesinclusive here is an example that matches an followed by three to six 'sre sub( 'ab{ , ''''abb abbb abbbb abbbbbbbbb ''abb *bbbherewe do not match abb because the is only followed by two ' the next two pieces get matchedas the is followed by three ' in the second termand four ' in the third in the last piecethere is an followed by nine ' what gets matched isthe along with the first six ' note that the matching in the last piece above is greedythat isit takes as many ' as it is allowed it is allowed to take between three and six 'sand it takes all six to get the opposite behaviorto get it take as few ' as allowedadd ?like belowre sub( 'ab{ , }''''abb abbb abbbb abbbbbbbbb ''abb *bbbbbbthe can go after any of the numeric specifierslike +?-???etc the character the character acts as an "or here is an example
9,363
regular expressions re sub( 'abc|xyz ''''abcdefxyz abc ''*def* *in the above exampleevery time we encounter an abc or an xyzwe replace it with an asterisk matching only at the start or end sometimes you don' want to match every occurrence of somethingmaybe just the first or the last occurrence to match just the first occurrence of somethingstart the pattern off with the character to match just the last occurrenceend the pattern with the character here are some examplesre sub'^abc ''''abcdefgabc 're sub'abc''''abcdefgabc '*defgabc abcdefgescaping special characters we have seen that and have special meanings what if we need to match plus signto do souse the backslash to escape itlike \here is an examplere sub( 'ab\''''ab+ '* alsoin pattern\ represents newline just note again about raw strings--if we didn' use them for the patternsevery backslash would have to be doubled for instancer'ab\+would have to be 'ab\\backslash sequences \ matches any digitand \ matches any non-digit here is an examplere sub( '\ '''' 're sub( '\ '''' '** *** *** \ matches any letter or numberand \ matches anything else here is an examplere sub( '\ ''''this is test re sub( '\ ''''this is test or is it'or is it''***********?'this*is* *test***or*is*it*this is good way to work with words \ matches whitespaceand \ matches non-whitespace here is an example
9,364
re sub( '\ ''''this is test re sub( '\ ''''this is test or is it'or is it''this*is* *test **or*is*it?'*************preceding and following matches sometimes you want to match things if they are preceded or followed by something code description (?=matches only if followed by (?!matches only if not followed by (?<=matches only if preceded by (?<!matches only if not preceded by here is an example that matched the word the only if it is followed by catre sub( 'the(?cat''''the dog and the cat ''the dog and cathere is an example that matches the word the only if it is preceded by spacere sub( '(?<)the ''''athens is the capital 'athens is capital the following example will match the word the only if it neither preceded by and nor followed by lettersso you can use it to replace occurrences of the word thebut not occurrences of the within other words re sub( '(?<!\ )[tt]he(?!\ ''''the cat is on the lathe there 'cat is on lathe there flags there are few flags that you can use to affect the behavior of regular expression we look at few of them here (? -this is to ignore case here is an examplere sub'(? )ab ''''ab ab '(? -recall the character matches any character except newline this flag makes it match newline characterstoo
9,365
regular expressions (? -regular expressions can be long and complicated this flag allows you to use more verbosemulti-line formatwhere whitespace is ignored you can also put comments in here is an examplepattern """(? )[ab]\dmatch or followed by some digits [cd]\dmatch or followed by some digits ""print(re sub(pattern''' and ')and summary there is lot to remember here is summaryexpression description [any of the characters inside the brackets any character except the newline or more of the preceding or more of the preceding or of the preceding {mexactly of the preceding { ,nbetween and (inclusiveof the preceding following +*?{ }and { , -take as few as possible escape special characters "or(at start of patternmatch just the first occurrence (at end of patternmatch just the last occurrence \ \ any digit (non-digit\ \ any letter or number (non-letter or -number\ \ any whitespace (non-whitespace(?=only if followed by (?!only if not followed by (?<=only if preceded by (?<!only if not preceded by (?iflag to ignore case (?sflag to make the match newlinestoo (?xflag to enable verbose style
9,366
here are some short examplesexpression description 'abcthe exact string abc '[abc]an abor '[ -za- ][ - ]match letter followed by digit '[ ] followed by any two characters (except newlines' +one or more ' ' *' ?any number of 'seven none zero or one ' { }exactly two ' ' { , }twothreeor four ' ' +?one or more ' taking as few as possible 'aa followed by period 'ab|zyan ab or zy '^afirst ' $last '\devery digit '\wevery letter or number '\severy whitespace '\deverything except digits '\weverything except letters and numbers '\severything except whitespace ' (?= )every followed by ' (?! )every not followed by '(?<= )aevery preceded by '(?<! )aevery not preceded by note note that in all of the examples in this we are dealing with non-overlapping patterns for instanceif we look for the pattern 'abain the string 'abababa'we see there are several overlapping matches all of our matching is done from the left and does not consider overlaps for instancewe have the followingre sub'aba ''''abababa ''*
9,367
regular expressions groups using parentheses around part of an expression creates group that contains the text that matches pattern you can use this to do more sophisticated substitutions here is an example that converts to lowercase every capital letter that is followed by lowercase letterdef modify(match)letters match group(return letters lower(re sub( '([ - ])[ - 'modify'peach apple apricot 'peach apple apricot the modify function ends up getting called three timesone for each time match occurs the re sub function automatically sends to the modify function match objectwhich we name match this object contains information about the matching text the object' group method returns the matching text itself if instead of match groupwe use match groupsthen we can further break down the match according the groups defined by the parentheses here is an example that matches capital letter followed by digit and converts each letter to lowercase and adds to each numberdef modify(match)letternumber match groups(return letter lower(str(int(number)+ re sub( '([ - ])(\ 'modify' ' the groups method returns the matching text as tuples for instancein the above program the tuples returned are shown belowfirst match(' '' 'second match(' '' 'third match(' '' 'note also that we can get at this information by passing arguments to match group for the first matchmatch group( is 'aand match group( is other functions sub -we have seen many examples of sub one thing we haven' mentioned is that there is an optional argument countwhich specifies how many matches (from the leftto make here is an examplere sub( ' ''''ababababa 'count= '* *bababa
9,368
findall -the findall function returns list of all the matches found here is an examplere findall( '[ab]\ '' '[' '' '' 'as another exampleto find all the words in stringyou can do the followingre findall( '\ 'sthis is better than using split(because split does not handle punctuationwhile the regular expression does split -the split function is analogous to the string method split the regular expression version allows us to split on something more general than the string method does here is an example that splits an algebraic expression at or re split( '\+|\'' + - ^ + '[' '' '' ^ '' 'match and search -these are useful if you just want to know if match occurs the difference between these two functions is match only checks to see if the beginning of the string matches the patternwhile search searches through the string until it finds match both return none if they fail to find match and match object if they do find match here are examplesif (re match( 'zzz ''abc zzz xyz '))print'match found at beginning 'elseprint'no match at beginning 'if (re search( 'zzz ''abc zzz xyz '))print'match found in string 'elseprint'no match found 'no match at beginning match found in string the match object returned by these functions has group information in it say we have the followinga=re search( '([abc])(\ '' + + ' group( group( group( ' ' ' remember that re search will only report on the first match it finds in the string
9,369
regular expressions finditer -this returns an iterator of match objects that we can loop throughlike belowfor in re finditer( '([ab])(\ '' + ')print( group( ) note that this is little more general than the findall function in that findall returns the matching stringswhereas finditer returns something like list of match objectswhich give us access to group information compile -if you are going to be reusing the same patternyou can save little time by first compiling the patternas shown belowpattern re compile( '[ab]\ 'pattern sub''' 'pattern sub' '' ' when you compile an expressionfor many of the methods you can specify optional starting and ending indices in the string here is an examplepattern re compile( '[ab]\ 'pattern findall' + + + ', , [' ' examples roman numerals numbers here we use regular expressions to convert roman numerals into ordinary import re ' ': 'cm ': ' ': 'cd ': ' ': 'xc ': ' ': 'xl ': ' ': 'ix ': ' ': 'iv ': ' ': pattern re compile( """(? ( { , })(cm)(cd)?( )?( { , }(xc)?(xl)?( )?( { , }(ix)?(iv)?( )?( { , })"""num input'enter roman numeral'upper( pattern match(numsum for in groups()
9,370
if !=none and !''if in 'cm ''cd ''xc ''xl ''ix ''iv ']sum+= [xelif [ in 'mdclxvi 'sum+= [ [ ]]*len(xprint(sumenter roman numeralmcmxvii the regular expression itself is fairly straightforward it looks for up to three 'sfollowed by zero or one cm'sfollowed by zero or one cd'setc and stores each of those in group the for loop then reads through those groups and uses dictionary to add the appropriate values to running sum dates here we use regular expression to take date in verbose formatlike february and convert it an abbreviated formatmm/dd/yy (with no leading zeroesrather than depend on the user to enter the date in exactly the right waywe can use regular expression to allow for variation and mistakes for instancethis program will work whether the user spells out the whole month name or abbreviates it (with or with periodcapitalization does not matterand it also does not matter if they can even spell the month name correctly they just have to get the first three letters correct it also does not matter how much space they use and whether or not they use comma after the day import re 'jan '' ''feb '' ''mar '' ''apr '' ''may '' ''jun '' ''jul '' ''aug '' ''sep '' ''oct '' ''nov '' ''dec '' 'date input'enter date' re match'([ -za- ]+)?\ *(\ { , }),?\ *(\ { }'dateprint'{}/{}/{format( [ group( lower()[: ]] group( ) group( )[- :])enter datefeb the first part of the regular expression([ -za- ]+)takes care of the month name it matches however many letters the user gives for the month name the matches either or periods after the month nameso the user can either enter period or not the parentheses around the letters save the result in group next we find the day\ *(\ { , }the first part \smatches zero or more whitespace charactersso it doesn' matter how much space the user puts between the month and day the rest matches one or two digits and saves it in group
9,371
regular expressions the rest of the expression,?\ *(\ { })finds the year then we use the results to create the abbreviated date the only tricky part here is the first partwhich takes the month namechanges it to all lowercaseand takes only the first three characters and uses those as keys to dictionary this wayas long as the user correctly spells the first three letters of the month namethe program will understand it
9,372
math this is collection of topics that are at somewhat mathematical in naturethough many of them are of general interest the math module as mentioned in section the math module contains some common math functions here are most of themfunction description sincostan trig functions asinacosatan inverse trig functions atan ( ,xgives arctany/xwith proper sign behavior sinhcoshtanh hyperbolic functions asinhacoshatanh inverse hyperbolic functions loglog natural loglog base log log( + )more accurate near than log exp exponential function degreesradians convert from radians to degrees or vice-versa floor floor(xis the greatest integer < ceil ceil(xis the least integer > epi the constants and factorial factorial modf returns pair (fractional partinteger partgammaerf the function and the error function
9,373
math note note that the floor and int functions behave the same for positive numbersbut differently for negative numbers for instancefloor( and int( both return the integer howeverfloor(- returns - the greatest integer less than or equal to - while int(- returns - which is obtained by throwing away the decimal part of the number atan the atan function is useful for telling the angle between two points let and be the distances between the points in the and directions the tangent of the angle in the picture below is given by / then arctany/xgives the angle itself but if the angle were this would not work as would be we would also need special cases to handle when and when the atan function handles all of this doing atan ( ,xwill return arctany/xwith all of the cases handled properly the atan function returns the result in radians if you would like degreesdo the followingangle math degrees(atan ( , )the resulting angle from atan is between - and (- and if you would like it between and do the followingangle math degrees(atan ( , )angle (angle+ scientific notation look at the following code ** + the resulting value is displayed in scientific notation it is the + stands for here is another example ** - this is -
9,374
comparing floating point numbers in section we saw that some numberslike are not represented exactly on computer mathematicallyafter the code below executesx should be but because of accumulated errorsit is actually for in range( ) + this means that the following if statement will turn out falseif == more reliable way to compare floating point numbers and is to check to see if the difference between the two numbers is sufficiently smalllike belowif abs( - )< - fractions there is module called fractions for working with fractions here is simple example of it in actionfrom fractions import fraction fraction( fraction( print( +sfraction( you can do basic arithmetic with fraction objectsas well as compare themtake their absolute valuesetc here are some further examplesr fraction( fraction( print(sprint(abs( * - )if >sprint' is larger 'fraction( , fraction( , is larger note that fraction automatically converts things to lowest terms the example below shows how to get the numerator and denominatorr fraction( , numerator denominator
9,375
math converting to and from floats belowto convert fraction to floating point numberuse floatlike float(fraction( ) on the other handsay we want to convert to fraction unfortunatelywe should not do fraction becauseas mentionedsome numbersincluding are not represented exactly on the computer in factfraction returns the following fraction objectfraction( insteaduse string notationlike belowfraction 'limiting the denominator one useful method is limit_denominator for given fraction objectlimit_denominator(xfinds the closest fraction to that value whose denominator does not exceed here is some examplesfraction 'limit_denominator( fraction 'limit_denominator( fraction' 'limit_denominator( fraction( fraction( fraction( the last example returns pretty close fractional approximation to it is off by less than greatest common divisor the fractions module contains useful function called gcd that returns the greatest common divisor of two numbers here is an examplefrom fractions import gcd print'the largest factor and have in common is 'gcd( )the largest factor and have in common is the decimal module python has module called decimal for doing exact calculations with decimal numbers as we've noted few times nowsome numberssuch as cannot be represented exactly as float here is
9,376
how to get an exact decimal representation of from decimal import decimal decimal 'decimal(' 'the string here is important if we leave it outwe get decimal that corresponds with the inexact floating point representation of decimal decimal(' 'math you can use the usual math operators to work with decimal objects for exampledecimal decimal decimal(' 'here is another exampledecimal( decimal( decimal(' 'the mathematical functions explnlog and sqrt are methods of decimal objects for instancethe following gives the square root of decimal( sqrt(decimal(' 'decimal objects can also be used with the built in maxminand sum functionsas well as converted to floats with float and strings with str precision by default decimal objects have -digit precision to change it tosayfive digitprecisionuse the getcontext function from decimal import getcontext getcontext(prec here is an example that prints out digits of getcontext(prec decimal( sqrt(decimal(' '
9,377
math there is theoretically no limit to the precision you can usebut the higher the precisionthe more memory is required and the slower things will run in generaleven with small precisionsdecimal objects are slower than floating point numbers ordinary floating point arithmetic is enough for most problemsbut it is nice to know that you can get higher precision if you ever need it there is lot more to the decimal module see the python documentation [ complex numbers python has data type for complex numbers in mathwe have - the number is called an imaginary number complex number is number of the form bi where and are real numbers the value is called the real partand is the imaginary part in electrical engineeringthe symbol is used in place of and in python is used for imaginary numbers here are couple of examples of creating complex numbersx complex( if number ends in or jpython treats it as complex number complex numbers have methods real(and imag(which return the real and imaginary parts of the number the conjugate method returns the complex conjugate (the conjugate of bi is bi the cmath module contains many of the same functions as the math moduleexcept that they work with complex arguments the functions include regularinverseand hyperbolic trigonometric functionslogarithms and the exponential function it also contains two functionspolar and rectfor converting between rectangular and polar coordinatescmath polar( jcmath rect( ( ( - + jcomplex numbers are fascinatingthough not all that useful in day-to-day life one nice applicationhoweveris fractals here is program that draws the famous mandelbrot set the program requires the pil and python or from tkinter import from pil import imageimagetkimagedraw def color_convert(rgb)return '#{ : }{ : }{ : xformat(int( * ),int( * )int( * )max_iter=
9,378
xtrans= ytrans= xzoom= yzoom=- root tk(canvas canvas(width= height= canvas grid(image=image new(mode'rgb ',size=( , )draw imagedraw draw(imagefor in range( )c_x ( - )/float(xzoom)+xtrans for in range( ) complex(c_x( - )/float(yzoom)+ytranscount= = while abs( )< and count<max_iterz * + count + draw point(( , )fill=color_convert(count+ ,count+ ,count+ )canvas delete(allphoto=imagetk photoimage(imagecanvas create_image( , ,image=photo,anchor=nwcanvas update(mainloop(the code here runs very slowly there are ways to speed it up somewhatbut python is unfortunately slow for these kinds of things
9,379
math more with lists and arrays sparse lists , , , , list of integers requires several hundred terabytes of storagefar more than most hard drives can store howeverin many practical applicationsmost of the entries of list are this allows us to save lot of memory by just storing the nonzero values along with their locations we can do this using dictionary whose keys are the locations of the nonzero elements and whose values are the values stored in the array at those locations for examplesuppose we have two-dimensional list whose entries are all zero except that [ ][ is and [ ][ is here is the dictionary that we would used {( , ) ( , ) the array module python has module called array that defines an array object that behaves lot like listexcept that its elements must all be the same type the benefit of array over lists is more efficient memory usage and faster performance see the python documentation [ for more about arrays the numpy and scipy libraries if you have any serious mathematical or scientific calculations to do on arraysyou may want to consider the numpy library it is easy to download and install from the numpy user' guidenumpy is the fundamental package for scientific computing in python it is python library that provides multidimensional array objectvarious derived objects (such as masked arrays and matrices)and an assortment of routines for fast operations on arraysincluding mathematicallogicalshape manipulationsortingselectingi/odiscrete fourier transformsbasic linear algebrabasic statistical operationsrandom simulation and much more there is also scipywhich builds off of numpy this time from the scipy user' guidescipy is collection of mathematical algorithms and convenience functions built on the numpy extension for python it adds significant power to the interactive python session by exposing the user to high-level commands and classes for the manipulation and visualization of data with scipyan interactive python session becomes data-processing and system-prototyping environment rivaling sytems such as matlabidloctaver-laband scilab random numbers how python generates random numbers the random number generator that python uses is called the mersenne twister it is reliable and well-tested it is deterministic generatormeaning
9,380
that it uses mathematical process to generate random numbers the numbers are called pseudorandom numbers becausecoming from mathematical processthey are not truly randomthoughfor all intents and purposesthey appear random anyone who knows the process can recreate the numbers this is good for scientific and mathematical applicationswhere you want to be able to recreate the same random numbers for testing purposesbut it is not suitable for cryptographywhere you need to generate truly random numbers seeds for mathematical and scientific applicationsyou may want to reproduce the same random numbers each time you run your programin order to test your work with the same data you can do this by specifying the seed examples are shown belowrandom seed( print("seed :"[random randint( , for in range( )]random seed( print("seed :"[random randint( , for in range( )]random seed( print("seed :",[random randint( , for in range( )]seed [ seed [ seed [ the seed can be any integer if we just use random seed()then the seed will be more or less randomly selected based off of the system clock the random function most of the functions in the random module are based off of the random functionwhich uses the mersenne twister to generate random numbers between and mathematical transformations are then used on the result of random to get some of the more interesting random number functions other functions in the random module the random module contains functions that return random numbers from various distributionslike the gaussian or exponential distributions for instanceto generate gaussian (normalrandom variableuse the gauss function here are some examplesrandom gauss( , [round(random gauss( , ), for in range( ) [ the first argument of gauss is the mean and the second is the standard deviation if you're not familiar with normal random variablesthey are the standard bell curve things like heights and sat scores and many other real-life things approximately fit this distribution in the example abovethe random numbers generated are centered around numbers closer to are more likely to be generated than numbers farther away
9,381
math there are bunch of other distributions that you can use the most common is the uniform distributionin which all values in range are equally likely for instancerandom uniform( , see the python documentation [ for information on the other distributions more random randint function one way to generate cryptographically safe random numbers is to use some fairly random physical process examples include radioactive decayatmospheric phenomenaand the behavior of certain electric circuits the os module has function urandom that generates random numbers from physical process whose exact nature depends on your system the urandom function takes one argument telling it how many bytes of random data to produce calling urandom( produces one byte of datawhich we can translate to an integer between and calling urandom( produces two bytes of datatranslating to integers between and here is function that behaves like randintbut uses urandom to give us nondeterministic random numbersfrom os import urandom from math import log def urandint( , ) urandom(int(log( - + )/log( ))+ total for ( ,yin enumerate( )total + *( **ireturn total%( - + )+ the way this works is we first have to determine how many bytes of random data to generate since one byte gives possible values and two bytes give possible valuesetc we compute the log base of the size of the range - + to determine how many byes to generate we then loop through the bytes generated and convert them to an integer finallymodding that integer by - + reduces that integer to number between and - + and adding to that produces an integer in the desired range miscellaneous topics hexadecimaloctaland binary python has built-in functions hexoctand bin for converting integers to hexadecimaloctaland binary the int function converts those bases to base here are some exampleshex( oct( bin( int( xfa' xfa
9,382
' ' hexadecimal values are prefaced with xoctal values are prefaced with and binary values are prefaced with the int function the int function has an optional second argument that allows you to specify the base you are converting from here are few examplesint' ' int' ' int' ' int' ' convert from base convert from base convert from base convert from base the pow function python has built-in function called powwhich raises numbers to powers it behaves like the *operatorexcept that it takes an optional third argument that specifies modulus thus pow( , ,nreturns ( ** )% the reason you might want to use this is that the pow way is much quicker when very large numbers are involvedwhich happens lot in cryptographic applications using the python shell as calculator often use the python shell as calculator this section contains few tips for working at the shell importing math functions one good way to start session at the shell is to import some math functionsfrom math import special variable there is special variable which holds the value of the previous calculation here is an example ** +
9,383
math logarithms use the natural logarithm lotand it is more natural for me to type ln instead of log if you want to do thatjust do the followingln log summing series here is way to get an approximate sum of seriesin this case = - sum([ /( ** - for in range( , )] another examplesay you need the sine of each of the angles and here is quick way to do that[round(sin(radians( )), for in range( , , )[ third-party modules there are number of other third-party modules that you might find useful when working in the python shell for instancethere is numpy and scipywhich we mentioned in section there is also matplotliba versatile library for plotting thingsand there is sympywhich does symbolic computations
9,384
working with functions this covers number of topics to do with functionsincluding some topics in functional programming first-class functions python functions are said to be first-class functionswhich means they can be assigned to variablescopiedused as arguments to other functionsetc just like any other object copying functions here is an example where we make copy of functiondef ( )return * print' ( ' ( )' ( ' ( )sep '\ ' ( ( lists of functions nextwe have list of functionsdef ( )return ** def ( )return ** funcs [fgprint(funcs[ ]( )funcs[ ]( )sep'\ '
9,385
working with functions here is another example say you have program with ten different functions and the program has to decide at runtime which function to use one solution is to use ten if statements shorter solution is to use list of functions the example below assumes that we have already created functions that each take two arguments funcs [ num eval(input'enter number')funcs[num](( , )functions as arguments to functions say we have list of -tuples if we sort the listthe sorting is done based off of the first entry as belowl [( , )( , )( , )( , ) sort([( )( )( )( )suppose we want the sorting to be done based off the second entry the sort method takes an optional argument called keywhich is function that specifies how the sorting should be done here is how to sort based off the second entrydef comp( )return [ [( , )( , )( , )( , ) sort(key=comp[( )( )( )( )here is another examplewhere we sort list of strings by lengthrather than alphabetically 'this ''is '' ''test ''of ''sorting ' sort(key=len[' ''is''of''this''test''sorting'one other place we have seen functions as arguments to other functions is the callback functions of tkinter buttons anonymous functions in one of the examples abovewe passed comparison function to the sort method here is the code againdef comp( )return [ sort(key=compif we have really short function that we're only going to use oncewe can use what is called an anonymous functionlike below
9,386
sort(key=lambda xx[ ]the lambda keyword indicates that what follows will be an anonymous function we then have the arguments to the functionfollowed by colon and then the function code the function code cannot be longer than one line we used anonymous functions back when working with guis to pass information about which button was clicked to the callback function here is the code againfor in range( )for in range( ) [ ][jbutton(command lambda = , =jfunction( , ) recursion recursion is the process where function calls itself one of the standard examples of recursion is the factorial function the factorialn!is the product of all the numbers from up to for instance * * * * alsoby convention recursion involves defining function in terms of itself notice thatfor example !and in generalnn ( )so the factorial function can be defined in terms of itself here is recursive version of the factorial functiondef fact( )if == return elsereturn *fact( - we must specify the case or else the function would keep calling itself forever (or at least until python generates an error about too many levels of recursionnote that the math module has function called factorialso this version here is just for demonstration note also that there is non-recursive way to do the factorialusing for loop it is about as straightforward as the recursive waybut faster howeverfor some problems the recursive solution is the more straightforward solution herefor exampleis program that factors number into prime factors def factor(numl=[])for in range( ,num// + )if num% == return +[ ]+factor(num//ireturn +[numthe factor function takes two argumentsa number to factorand list of previously found factors it checks for factorand if it finds oneit appends it to the list the recursive part is that it divides the number by the factor that was found and then appends to the list all the factors of that value on the other handif the function doesn' find any factorsit appends the number to the listas it must be primeand returns the new list
9,387
working with functions mapfilterreduceand list comprehensions map and filter python has built-in functions called map and filter that are used to apply functions to the contents of list they date back to before list comprehensions were part of pythonbut now list comprehensions can accomplish everything these functions can stillyou may occasionally see code using these functionsso it is good to know about them the map function takes two arguments-- function and an iterable--and it applies the function to each element of the iterablegenerating new iterable here is an example that takes list of strings returns list of the lengths of the strings the first line accomplishes this with mapwhile the second line uses list comprehensionsl list(map(len'this ''is '' ''test ']) [len(wordfor word in 'this ''is '' ''test ']the function filter takes function and an iterable and returns an iterable of all the elements of the list for which the function is true here is an example that returns all the words in list that have length greater than the first line uses filter to do thisand the second line does it with list comprehensionl list(filter(lambda xlen( )> 'this ''is '' ''test ']) [word for word in 'this ''is '' ''test 'if len(word)> here is one approach to finding the number of items in list that are greater than count= for in lif > count count here is second way using list comprehension similar to the filter functionlen([ for in if > ]the second way is both shorter and easier to understand reduce there is another functionreducethat applies function to the contents of list it used to be built-in functionbut in python it has also been moved to the functools module this function cannot be easily replaced with list comprehensions to understand itfirst consider simple example that adds up the numbers from to total for in range( , )total total the reduce function can be used to do this in single linetotal reduce(lambda ,yx+yrange( , )in generalreduce takes function and an iterableand applies the function to the elements from left to rightaccumulating the result as another simple examplethe factorial function could be implemented using reduce
9,388
def fact( )return reduce(lambda , : *yrange( , + ) the operator module in the previous sectionwhen we needed function to represent python operator like addition or multiplicationwe used an anonymous functionlike belowtotal reduce(lambda ,yx+yrange( , )python has module called operator that contains functions that accomplish the same thing as python operators these will run faster than anonymous functions we can rewrite the above example like thisfrom operator import add total reduce(addrange( , )the operator module has functions corresponding arithmetic operatorslogical operatorsand even things like slicing and the in operator more about function arguments you may want to write function for which you don' know how many arguments will be passed to it an example is the print function where you can enter however many things you want to printeach separated by commas python allows us to declare special argument that collects several other arguments into tuple this syntax is demonstrated belowdef product(*nums)prod for in numsprod*= return prod print(product( , )product( , , )sep'\ ' there is similar notation**for collecting an arbitrary number of keyword arguments into dictionary here is simple exampledef (**keyargs)for in keyargsprint( '** 'keyargs[ ]** sep'' ( = = = **
9,389
working with functions ** ** you can also use these notations together with ordinary arguments the order matters--arguments collected by have to come after all positional arguments and arguments collected by *always come last two example function declarations are shown belowdef func(abc= * ** )def func(ab*cd= ** )calling functions examplethe and *notations can be used when calling functiontoo here is an def ( , )print( +bx=( , (*xthis will print in this case we could have more simply called ( , )but there are situations when that is not possible for examplemaybe you have several different sets of arguments that your program might use for function you could have several if statementsbut if there are lot of different sets of argumentsthen the notation is much easier here is simple exampledef ( , )print( +bargs [( , )( , )( , )( , )( , ) eval(input'enter number from to ') (*args[ ]one use for the *notation is simplifying tkinter declarations suppose we have several widgets that all have the same propertiessay the same fontforeground colorand background color rather than repeating those properties in each declarationwe can save them in dictionary and then use the *notation in the declarationslike belowargs 'fg ''blue ''bg ''white ''font ':'verdana ' 'bold ')label label(text'label '**argslabel label(text'label '**argsapply python has function called apply which ismore or lessthe equivalent of and *for calling functions you may see it in older code function variables that retain their values between calls sometimes it is useful to have variables that are local to function that retain their values between function calls since functions are objectswe can accomplish this by adding variable to the function as if it were more typical sort of object in the example below the variable count keeps track of how many times the function is called def () count count+ print( countf count=
9,390
the itertools and collections modules the itertools and collections modules contain functions that can greatly simplify some common programming tasks we will start with some functions in itertools permutations and combinations permutations the permutations of sequence are rearrangements of the items of that sequence for examplesome permutations of [ , , are [ , , and [ , , here is an example that shows all the possibilitieslist(permutations([ , , ])[( , , )( , , )( , , )( , , )( , , )( , , )we can find the permutations of any iterable here are the permutations of the string ' ''join(pfor in permutations' ')[' '' '' '' '' '' 'the permutations function takes an optional argument that allows us to specify the size of the permutations for instanceif we just want all the two-element substrings possible from ' 'we can do the following'join(pfor in permutations' ' )[' '' '' '' '' '' 'note that permutations and most of the other functions in the itertools module return an iterator you can loop over the items in an iterator and you can use list to convert it to list
9,391
the itertools and collections modules combinations if we want all the possible -element subsets from sequencewhere all that matters is the elementsnot the order in which they appearthen what we want are combinations for instancethe -element subsets that can be made from { are { }{ and { we consider { and { as being the same because they contain the same elements here is an example showing the combinations of two-element substrings possible from ' ''join(cfor in combinations' ' )[' '' '' 'combinations with replacement for combinations with repeated elementsuse the function combinations_with_replacement 'join(cfor in combinations_with_replacement' ' )[' '' '' '' '' '' ' cartesian product the function product produces an iterator from the cartesian product of iterables the cartesian product of two sets and consists of all pairs (xywhere is in and is in here is short example'join(pfor in product'abc '' ')[' '' '' '' '' '' '' '' '' 'example to demonstrate the use of producthere are three progressively shorterand clearer ways to find all oneor two-digit pythagorean triples (values of (xyzsatisfying the first way uses nested for loopsfor in range( , )for in range( , )for in range( , )if ** + ** == ** print( , ,zhere is the same thing rewritten with productx range( , for ( , ,zin product ( , , )if ** + ** == ** print( , ,zit is even shorter if we use list comprehensionsx range( , [( , ,zfor ( , ,zin product( , ,xif ** + ** == **
9,392
grouping things the groupby function is handy for grouping things it breaks list up into groups by tracing through the list and every time there is change in valuesa new group is created the groupby function returns ordered pairs that consist of list item and groupby iterator object that contains the group of items [ for key,group in groupby( )print(key''list(group) [ [ [ [ [ notice that we get two groups of zeros this is because groupby returns new group each time there is change in the list in the above exampleif we instead just wanted to know how many of each number occurwe can first sort the list and then call groupby [ sort(for key,group in groupby( )print(key''len(list(group)) most of the timeyou will want to sort your data before calling groupby optional argument the groupby function takes an optional argument that is function telling it how to group things when using thisyou usually have to first sort the list with that function as the sorting key here is an example that groups list of words by lengthl 'this ''is '' ''test ''of ''groupby ' sort(key lenfor key,group in groupby(llen)print(key''list(group) ' ['is''of' ['test''this' ['groupby'examples we close this section with two examples
9,393
the itertools and collections modules firstsuppose is list of zeros and onesand we want to find out how long the longest run of ones is we can do that in one line using groupbymax([len(list(group)for key,group in groupby(lif key== ]secondsuppose we have function called easter that returns the date of easter in given year the following code will produce histogram of which dates occur most often from to [easter(yfor in range( , ) sort(for key,group in groupby( )print(key''''*(len(list(group)) miscellaneous things from itertools chain the chain function chains iterators together into one big iterator for exampleif you have three listslmand and want to print out all the elements of eachone after anotheryou can do the followingfor in chain( , , )print(ias another examplein section we used list comprehensions to flatten list of liststhat is to return list of all the elements in the lists here is another way to do that using chainl [[ , , ][ , , ][ , , ]list(chain(*tuple( ))[ count the function count(behaves like range(it takes an optional argument so that count(xbehaves like range( ,cycle the cycle function cycles over the elements of the iterator continuously when it gets to the endit starts over at the beginningand keeps doing this forever the following simple example prints the numbers through continuously until the user enters an ' 'for in cycle(range( )) input'keep goingy or 'if =' 'break print(xmore about iterators there are number of other functions in the itertools module see the python documentation [ for more it has nice table summarizing what the various functions do
9,394
counting things the collections module has useful class called counter you feed it an iterable and the counter object that is created is something very much like dictionary whose keys are items from the sequence and whose values are the number of occurrences of the keys in factcounter is subclass of dictpython' dictionary class here is an examplecounter'aababcabcdabcde 'counter({' ' ' ' ' ' ' ' ' ' }since counter is subclass of dictyou can access items just like in dictionaryand most of the usual dictionary methods work for examplec counter'aababcabcdabcde ' ' 'list( keys()list( values() 'acbed [ getting the most common items this most_common method takes an integer and returns list of the most common itemsarranged as (keyvaluetuples for examplec counter'aababcabcdabcde ' most_common( [(' ' )(' ' )if we omit the argumentit returns tuples for every itemarranged in decreasing order of frequency to get the least common elementswe can use slice from the end of the list returned by most_common here is some examplesc counter'aababcabcdabcde ' most_common( most_common()[- : most_common()[- ::- [(' ' )(' ' )(' ' )(' ' )(' ' )[(' ' )(' ' )[(' ' )(' ' )(' ' )(' ' )the last example uses negative slice index to reverse the order to least to most common an example here is really short program that will scan through text file and create counter object of word frequencies
9,395
the itertools and collections modules from collections import counter import re open'filename txtread(words re findall'\ ' lower() counter(wordsto print the ten most common wordswe can do the followingfor wordfreq in most_common( )print(word''freqto pick out only those words that occur more than five timeswe can do the following[word for word in if [word]> math with counters you can use some operators on counter objects here is some examplesc counter'aabbb ' counter'abccc ' + - & | counter({' ' ' ' ' ' }counter({' ' ' ' }counter({' ' ' ' }counter({' ' ' ' ' ' }doing + combines the counts from and dwhereas - subtracts the counts from from the corresponding counts of note that the counter returned by - does not include or negative counts the stands for intersection and returns the minimum of the two values for each itemand stands for union and returns the maximum of the two values defaultdict the collections module has another dictionary-like class called defaultdict it is almost exactly like an ordinary dictionary except that when you create new keya default value is given to the key here is an example that mimics what the counter class does 'aababcabcdabcd dd defaultdict(intfor in sdd[ ]+= defaultdict({' ' ' ' ' ' ' ' }
9,396
if we had tried this with dd just regular dictionarywe would have gotten an error the first time the program reached dd[ ]+= because dd[cdid not yet exist but since we declared dd to be defaultdict(int)each value is automatically assigned value of upon creationand so we avoid the error note that we could use regular dictionary if we add an if statement into the loopand there is also function of regular dictionaries that allows you to set default valuebut defaultdict runs faster we can use types other than integers here is an example with stringss 'aababcabcdabcd dd defaultdict(strfor in sdd[ ]+'defaultdict({' ''*****'' ''***'' ''****'' ''**'}use list for listsset for setsdict for dictionariesand float for floats you can use various other classestoo the default value for integers is for lists is []for sets is set()for dictionaries is {and for floats is if you would like different default valueyou can use an anonymous function like belowdd defaultdict(lambda: used with the code from the first examplethis will producedefaultdict({' ' ' ' ' ' ' ' }
9,397
the itertools and collections modules
9,398
exceptions this provides brief introduction to exceptions basics if you are writing program that someone else is going to useyou don' want it to crash if an error occurs say your program is doing bunch of calculationsand at some point you have the line = / if ever happens to be you will get division by zero error and the program will crash here is an examplea / print'hi there 'zerodivisionerrorint division or modulo by zero once the error occursnone of the code after = / will get executed in factif the user is not running the program in idle or some other editorthey won' even see the error the program will just stop running and probably close when an error occursan exception is generated you can catch this exception and allow your program to recover from the error without crashing here is an examplea tryc= / except zerodivisionerrorprint'calculation error 'print'hi there 'calculation error
9,399
exceptions hi there different possibilities we can have multiple statements in the try block and also and multiple except blockslike belowtrya eval(input'enter number')print ( /aexcept nameerrorprint'please enter number 'except zerodivisionerrorprint("can ' enter "not specifying the exception you can leave off the name of the exceptionlike belowtrya eval(input'enter number')print ( /aexceptprint' problem occurred 'it is generally not recommended that you do thishoweveras this will catch every exceptionincluding ones that maybe you aren' anticipating when you write the code this will make it hard to debug your program using the exception when you catch an exceptioninformation about the exception is stored in an exception object below is an example that passes the name of the exception to the usertryc / except exception as eprint(eint division or modulo by zero try/except/else you can use an else clause along with try/except here is an exampletryfile open'filename txt '' 'except ioerrorprint'could not open file 'elses file read(print(