id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
6,900 | the program loads the data for the maze' walls from text file and into dictionary stored in the maze variable this dictionary has (xytuples for keys and the string in the wallemptystartor exit constants for values project "maze runner ,uses similar dictionary representation of the maze the difference between the projects is in the code that renders that maze on the screen since maze runner is simpleri recommend becoming familiar with this program first before moving on to maze runner """maze runner dby al sweigart al@inventwithpython com move around maze and try to escape maze files are generated by mazemakerrec py view this code at tagslargegamemaze"" import sysos maze file constants wall '# empty start ' exit ' player '@(!try changing this to '+or ' block chr( character is '# def displaymaze(maze) display the maze for in range(height) for in range(width) if (xy=(playerxplayery) print(playerend='' elif (xy=(exitxexity) print(' 'end='' elif maze[(xy)=wall print(blockend='' else print(maze[(xy)]end='' print(print newline after printing the row print('''maze runner dby al sweigart al@inventwithpython com (maze files are generated by mazemakerrec py)''' get the maze file' filename from the user while true print('enter the filename of the maze (or list or quit):' filename input('' list all the maze files in the current foldermaze runner |
6,901 | if filename upper(='list' print('maze files found in'os getcwd() for fileincurrentfolder in os listdir() if (fileincurrentfolder startswith('maze'and fileincurrentfolder endswith(txt')) print('fileincurrentfolder continue if filename upper(='quit' sys exit( if os path exists(filename) break print('there is no file named'filename load the maze from file mazefile open(filename maze { lines mazefile readlines( playerx none playery none exitx none exity none for line in lines width len(line rstrip() for xcharacter in enumerate(line rstrip()) assert character in (wallemptystartexit)'invalid character at column {}line {}format( if character in (wallempty) maze[(xy)character elif character =start playerxplayery xy maze[(xy)empty elif character =exit exitxexity xy maze[(xy)empty + height assert playerx !none and playery !none'no start in maze file assert exitx !none and exity !none'no exit in maze file while truemain game loop displaymaze(maze while trueget user move print( ' print('enter directionor quitasd' move input(''upper( if move ='quit' print('thanks for playing!' sys exit( project # |
6,902 | if move not in [' '' '' '' ']print('invalid direction enter one of wasor 'continue check if the player can move in that directionif move ='wand maze[(playerxplayery )=emptybreak elif move ='sand maze[(playerxplayery )=emptybreak elif move ='aand maze[(playerx playery)=emptybreak elif move ='dand maze[(playerx playery)=emptybreak print('you cannot move in that direction 'keep moving in this direction until you encounter branch point if move =' 'while trueplayery - if (playerxplayery=(exitxexity)break if maze[(playerxplayery )=wallbreak break if we've hit wall if (maze[(playerx playery)=empty or maze[(playerx playery)=empty)break break if we've reached branch point elif move =' 'while trueplayery + if (playerxplayery=(exitxexity)break if maze[(playerxplayery )=wallbreak break if we've hit wall if (maze[(playerx playery)=empty or maze[(playerx playery)=empty)break break if we've reached branch point elif move =' 'while trueplayerx - if (playerxplayery=(exitxexity)break if maze[(playerx playery)=wallbreak break if we've hit wall if (maze[(playerxplayery )=empty or maze[(playerxplayery )=empty)break break if we've reached branch point elif move =' 'while trueplayerx + if (playerxplayery=(exitxexity)break if maze[(playerx playery)=wallbreak break if we've hit wall if (maze[(playerxplayery )=empty maze runner |
6,903 | or maze[(playerxplayery )=empty)break break if we've reached branch point if (playerxplayery=(exitxexity)displaymaze(mazeprint('you have reached the exitgood job!'print('thanks for playing!'sys exit(exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what error message do you get if you change character =start on line to character =exit what happens if you change playery on line to playery what happens if you change (exitxexityon line to (nonenone) what error message do you get if you change while trueon line to while false: what happens if you change break on line to continue what error message do you get if you change break on line to continue project # |
6,904 | ma ze runner this three-dimensional maze runner provides the player with first-person view from inside maze try to find your way outyou can generate maze files by following the instructions in project "maze runner ,or by downloading maze files from |
6,905 | when you run mazerunner pythe output will look like thismaze runner dby al sweigart al@inventwithpython com (maze files are generated by mazemakerrec pyenter the filename of the maze (or list or quit)maze txt ###############\|###############location ( directionnorth (wenter direction( (dor quit ###############\|###############location ( directioneast --snip-how it works this -perspective ascii art starts with the multiline string stored in all_open this string depicts position in which no paths are closed off by walls the program then draws the wallsstored in the closed dictionaryon top of the all_open string to generate the ascii art for any possible combination of closed-off paths for examplehere' how the program generates the view in which the wall is to the left of the player project # |
6,906 | ____ |/||||__ __|||/|| |||\||| \ |||___|\|___ \ \ ____ /||__ __||/| ||\|| \ ||\|___ the periods in the ascii art in the source code get removed before the strings are displayedthey only exist to make entering the code easierso you don' insert or leave out blank spaces here is the source code for the maze """maze dby al sweigart al@inventwithpython com move around maze and try to escape in view this code at tagsextra-largeartisticgamemaze"" import copysysos set up the constants wall '# empty start ' exit ' block chr( character is '# north 'north south 'south east 'east west 'west def wallstrtowalldict(wallstr) """takes string representation of wall drawing (like those in all_open or closedand returns representation in dictionary with (xytuples as keys and single-character strings of the character to draw at that xy location "" walldict { height width for yline in enumerate(wallstr splitlines()) if height height for xcharacter in enumerate(line) if width width walldict[(xy)character walldict['height'height maze runner |
6,907 | walldict['width'width return walldict exit_dict {( )' '( )' '( )' ' ( )' ''height' 'width' the way we create the strings to display is by converting the pictures in these multiline strings to dictionaries using wallstrtowalldict( then we compose the wall for the player' location and direction by "pastingthe wall dictionaries in closed on top of the wall dictionary in all_open all_open wallstrtowalldict( '' ____ ____ |/ || ||__ __| ||/| | | ||\| || \ | || ___|\|___ ''strip() the strip(call is used to remove the newline at the start of this multiline string closed { closed[' 'wallstrtowalldict( '' ''strip()paste to closed[' 'wallstrtowalldict( '' ''strip()paste to closed[' 'wallstrtowalldict( '' project # |
6,908 | ''strip()paste to closed[' 'wallstrtowalldict( '' ''strip()paste to closed[' 'wallstrtowalldict( '' \ ''strip()paste to closed[' 'wallstrtowalldict( '' ''strip()paste to def displaywalldict(walldict) """display wall dictionaryas returned by wallstrtowalldict()on the screen "" print(block (walldict['width' ) for in range(walldict['height']) print(blockend='' for in range(walldict['width']) wall walldict[(xy) if wall =' wall print(wallend='' print(blockprint block with newline print(block (walldict['width' )maze runner |
6,909 | def pastewalldict(srcwalldictdstwalldictlefttop) """copy the wall representation dictionary in srcwalldict on top of the one in dstwalldictoffset to the position given by lefttop "" dstwalldict copy copy(dstwalldict for in range(srcwalldict['width']) for in range(srcwalldict['height']) dstwalldict[( lefty top)srcwalldict[(xy) return dstwalldict def makewalldict(mazeplayerxplayeryplayerdirectionexitxexity) """from the player' position and direction in the maze (which has an exit at exitxexity)create the wall representation dictionary by pasting wall dictionaries on top of all_openthen return it "" the - "sections(which are relative to the player' direction determine which walls in the maze we check to see if we need to paste them over the wall representation dictionary we're creating if playerdirection =north map of the sectionsrelative to the player @bcd (player facing north @ offsets ((' ' - )(' '- - )(' ' - ) (' ' - )(' '- )(' ' ) if playerdirection =south map of the sectionsrelative @ to the player @dcb (player facing south offsets ((' ' )(' ' )(' ' ) (' '- )(' ' )(' '- ) if playerdirection =east map of the sectionsrelative eb to the player @@ca (player facing east fd offsets ((' ' )(' ' - )(' ' ) (' ' )(' ' - )(' ' ) if playerdirection =west map of the sectionsrelative df to the player @ac(player facing west be offsets ((' '- )(' '- )(' '- ) (' '- - )(' ' )(' ' - ) section { for secxoffyoff in offsets section[secmaze get((playerx xoffplayery yoff)wall if (playerx xoffplayery yoff=(exitxexity) section[secexit walldict copy copy(all_open paste_closed_to {' '( )' '( )' '( ) ' '( )' '( )' '( ) project # |
6,910 | for sec in 'abdcef' if section[sec=wall walldict pastewalldict(closed[sec]walldict paste_closed_to[sec][ ]paste_closed_to[sec][ ] draw the exit sign if needed if section[' '=exit walldict pastewalldict(exit_dictwalldict if section[' '=exit walldict pastewalldict(exit_dictwalldict if section[' '=exit walldict pastewalldict(exit_dictwalldict return walldict print('maze runner dby al sweigart al@inventwithpython com' print('(maze files are generated by mazemakerrec py)' get the maze file' filename from the user while true print('enter the filename of the maze (or list or quit):' filename input('' list all the maze files in the current folder if filename upper(='list' print('maze files found in'os getcwd() for fileincurrentfolder in os listdir() if (fileincurrentfolder startswith('maze' and fileincurrentfolder endswith(txt')) print('fileincurrentfolder continue if filename upper(='quit' sys exit( if os path exists(filename) break print('there is no file named'filename load the maze from file mazefile open(filename maze { lines mazefile readlines( px none py none exitx none exity none for line in lines width len(line rstrip() for xcharacter in enumerate(line rstrip()) assert character in (wallemptystartexit)'invalid character at column {}line {}format( if character in (wallempty)maze runner |
6,911 | maze[(xy)character elif character =start pxpy xy maze[(xy)empty elif character =exit exitxexity xy maze[(xy)empty + height assert px !none and py !none'no start point in file assert exitx !none and exity !none'no exit point in file pdir north while truemain game loop displaywalldict(makewalldict(mazepxpypdirexitxexity) while trueget user move print('location ({}{}direction{}format(pxpypdir) print(( )' print('enter direction( (dor quit ' move input(''upper( if move ='quit' print('thanks for playing!' sys exit( if (move not in [' '' '' '' '' '' ' and not move startswith(' ')) print('please enter one of flor (or wad' continue move the player according to their intended move if move ='for move =' ' if pdir =north and maze[(pxpy )=empty py - break if pdir =south and maze[(pxpy )=empty py + break if pdir =east and maze[(px py)=empty px + break if pdir =west and maze[(px py)=empty px - break elif move ='lor move =' ' pdir {northwestwestsouth southeasteastnorth}[pdir break elif move ='ror move =' ' pdir {northeasteastsouth southwestwestnorth}[pdir break project # |
6,912 | elif move startswith(' ')cheat code' ,ypxpy move split()[ split(','px int(pxpy int(pybreak elseprint('you cannot move in that direction 'if (pxpy=(exitxexity)print('you have reached the exitgood job!'print('thanks for playing!'sys exit(exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what bug do you cause if you change move ='quiton line to move ='quit' how can you remove the teleportation cheatmaze runner |
6,913 | million dice roll tat at when you roll two six-sided dicethere' percent chance you'll roll that' much better than the odds of rolling just percent that' because there' only one combination of dice rolls that gives you (the one that occurs when both dice roll )but many combinations add up to seven and and and and so on but what about when you roll three diceor fouror , you could mathematically calculate the theoretical probabilitiesor you can have the computer roll number of dice one million times to empirically figure them out this program takes that latter approach in this programyou tell the computer to roll dice one million times and remember the results it then displays the percentage chance of each sum this program does massive amount of computationbut the computation itself isn' hard to understand |
6,914 | when you run milliondicestats pythe output will look like thismillion dice roll statistics simulator by al sweigart al@inventwithpython com enter how many six-sided dice you want to roll simulating , , rolls of dice done done total rolls percentage rolls rolls rolls rolls rolls rolls rolls rolls rolls rolls rolls how it works we simulate the roll of single six-sided die by calling random randint( on line this returns random number between and which gets added to the running total for however many dice are rolled together the random randint(function has uniform distributionmeaning each number is just as likely as any other to be returned the program stores the results of this roll with the results dictionary the keys to this dictionary are each possible dice roll totaland the values are how many times this total has been encountered to get the frequency percentagewe divide the number of times total has been encountered by , , (the number of dice rolls in this simulationand multiply it by (to get percentage between and instead of and by doing some algebrawe can figure out that this is the same as dividing the number of encounters by , which we do on line """million dice roll statistics simulator by al sweigart al@inventwithpython com simulation of one million dice rolls view this code at tagstinybeginnermathsimulation"" import randomtime print('''million dice roll statistics simulator by al sweigart al@inventwithpython com million dice roll statistics simulator |
6,915 | numberofdice int(input('') set up dictionary to store the results of each dice roll results { for in range(numberofdice(numberofdice ) results[ simulate dice rolls print('simulating , , rolls of {dice format(numberofdice) lastprinttime time time( for in range( ) if time time(lastprinttime print('{}done format(round( )) lastprinttime time time( total for in range(numberofdice) total total random randint( results[totalresults[total display results print('total rolls percentage' for in range(numberofdice(numberofdice ) roll results[ percentage round(results[ print({{rolls {}%format(irollpercentage)after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingtry rolling - - -or -sided dice try simulating two-sided coin tosses exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change lastprinttime on line to lastprinttime what bug do you cause if you delete or comment out results[totalresults[total on line what error happens if the user types letters instead of number for the number of six-sided dice to roll project # |
6,916 | at piet mondrian was th-century dutch painter and one of the founders of neoplasticisman abstract art movement his most iconic paintings relied on blocks of primary colors (blueyellowred)blackand white using minimalist approachhe separated these colors with horizontal and vertical elements this program generates random paintings that follow mondrian' style you can find out more about piet mondrian at piet_mondrian the program in action the bext module allows our python program to display bright primary colors in the text outputeven though this book only shows black-and-white images figure - shows what the output will look like when you run mondrian py |
6,917 | generated each time the program runs how it works the algorithm works by creating data structure (the canvas dictionarywith randomly spaced vertical and horizontal linesas in figure - figure - the first step of the mondrian art algorithm creates grid project # |
6,918 | as shown in figure - figure - the second step of the mondrian art algorithm removes some lines at random finallythe algorithm randomly fills some rectangles with yellowredblueor blackas in figure - figure - the third step of the mondrian art algorithm randomly selects rectangles to fill with color mondrian art generator |
6,919 | sample images """mondrian art generatorby al sweigart al@inventwithpython com randomly generates art in the style of piet mondrian more info at view this code at tagslargeartisticbext"" import sysrandom try import bext except importerror print('this program requires the bext modulewhich you' print('can install by following the instructions at' print(' sys exit( set up the constants min_x_increase max_x_increase min_y_increase max_y_increase white 'white black 'black red 'red yellow 'yellow blue 'blue setup the screen widthheight bext size( we can' print to the last column on windows without it adding newline automaticallyso reduce the width by one width - height - while truemain application loop pre-populate the canvas with blank spaces canvas { for in range(width) for in range(height) canvas[(xy)white generate vertical lines numberofsegmentstodelete random randint(min_x_increasemax_x_increase while width min_x_increase numberofsegmentstodelete + for in range(height) canvas[(xy)black +random randint(min_x_increasemax_x_increase project # |
6,920 | generate horizontal linesy random randint(min_y_increasemax_y_increasewhile height min_y_increasenumberofsegmentstodelete + for in range(width)canvas[(xy)black +random randint(min_y_increasemax_y_increasenumberofrectanglestopaint numberofsegmentstodelete numberofsegmentstodelete int(numberofsegmentstodelete randomly select points and try to remove them for in range(numberofsegmentstodelete)while truekeep selecting segments to try to delete get random start point on an existing segmentstartx random randint( width starty random randint( height if canvas[(startxstarty)=whitecontinue find out if we're on vertical or horizontal segmentif (canvas[(startx starty)=white and canvas[(startx starty)=white)orientation 'verticalelif (canvas[(startxstarty )=white and canvas[(startxstarty )=white)orientation 'horizontalelsethe start point is on an intersectionso get new random start pointcontinue pointstodelete [(startxstarty)candeletesegment true if orientation ='vertical'go up one path from the start pointand see if we can remove this segmentfor changey in (- ) starty while height +changey if (canvas[(startx )=black and canvas[(startx )=black)we've found four-way intersection break elif ((canvas[(startx )=white and canvas[(startx )=blackor (canvas[(startx )=black and canvas[(startx )=white))we've found -intersectionwe can' delete this segmentcandeletesegment false break mondrian art generator |
6,921 | project # elsepointstodelete append((startxy)elif orientation ='horizontal'go up one path from the start pointand see if we can remove this segmentfor changex in (- ) startx while width +changex if (canvas[(xstarty )=black and canvas[(xstarty )=black)we've found four-way intersection break elif ((canvas[(xstarty )=white and canvas[(xstarty )=blackor (canvas[(xstarty )=black and canvas[(xstarty )=white))we've found -intersectionwe can' delete this segmentcandeletesegment false break elsepointstodelete append((xstarty)if not candeletesegmentcontinue get new random start point break move on to delete the segment if we can delete this segmentset all the points to whitefor xy in pointstodeletecanvas[(xy)white add the border linesfor in range(width)canvas[( )black top border canvas[(xheight )black bottom border for in range(height)canvas[( )black left border canvas[(width )black right border paint the rectanglesfor in range(numberofrectanglestopaint)while truestartx random randint( width starty random randint( height if canvas[(startxstarty)!whitecontinue get new random start point elsebreak flood fill algorithmcolortopaint random choice([redyellowblueblack]pointstopaint set([(startxstarty)]while len(pointstopaint |
6,922 | xy pointstopaint pop(canvas[(xy)colortopaint if canvas[( )=whitepointstopaint add(( )if canvas[( )=whitepointstopaint add(( )if canvas[(xy )=whitepointstopaint add((xy )if canvas[(xy )=whitepointstopaint add((xy )draw the canvas data structurefor in range(height)for in range(width)bext bg(canvas[(xy)]print('end=''print(prompt user to create new onetryinput('press enter for another work of artor ctrl- to quit 'except keyboardinterruptsys exit(after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingcreate programs with different color palettes use the pillow module to produce image files of mondrian art you can learn about this module from of automate the boring stuff with python at exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what error happens if you change canvas[(xy)white on line to canvas[(xy)red what happens if you change print('end=''on line to print(' 'end='')mondrian art generator |
6,923 | mont hall problem the monty hall problem illustrates surprising fact of probability the problem is loosely based on the old game show let' make deal and its hostmonty hall in the monty hall problemyou can pick one of three doors behind one door is prizea new car each of the other two doors opens onto worthless goat say you pick door # before the door you choose is openedthe host opens another door (either # or # )which leads to goat you can choose to either open the door you originally picked or switch to the other unopened door it may seem like it doesn' matter if you switch or notbut your odds do improve if you switch doorsthis program demonstrates the monty hall problem by letting you do repeated experiments to understand why your odds improveconsider version of the monty hall problem with one thousand doors instead of three you pick one doorand then the host opens doorswhich all reveal goats the only two |
6,924 | you correctly picked the car door to begin with ( in , chance)then the host left random goat door closed if you picked goat door ( in , chance)the host specifically chose the car door to leave closed the choice of which doors to open isn' randomthe host knows to leave the car door closed it' almost certain that you didn' pick the car door to begin withso you should switch to the other door another way to think of it is that you have , boxes and one box contains prize you guess which box the prize is in and the host puts it in your hands do you think the prize is in your box or one of the other boxesyou don' need the host to open of the boxes that don' contain prizethe amount of choice is the same as with the , doors the odds that you guessed correctly in the beginning are in , while the odds that you did not (and that the prize is in one of the other boxesis near certain in , more information about the monty hall problem can be found at the program in action when you run montyhall pythe output will look like thisthe monty hall problemby al sweigart al@inventwithpython com --snip-+++ +++pick door or (or "quitto stop) +++( oo / /| |goat||+++door contains goatdo you want to swap doorsy/ +(oo / /| |goat||++car___/ __o ++(oo / /| |goat||+monty hall problem |
6,925 | you wonswapping wins lossessuccess rate not swapping wins lossessuccess rate press enter to repeat the experiment --snip-how it works the multiline strings for the ascii-art doors are stored in several constant variablessuch as all_closedfirst_goatand first_car_others_goat the code that uses these constantslike print(first_goaton line stays the same even if we update the graphics by placing the multiline strings together toward the top of the source code filewe'll have an easier time comparing them to make sure the graphics are consistent """the monty hall problemby al sweigart al@inventwithpython com simulation of the monty hall game show problem more info at view this code at tagslargegamemathsimulation"" import randomsys all_closed "" +++ ++++"" first_goat "" +++ ( oo / /| |goat|| ++++"" second_goat "" +++ ( oo / /| |goat|| ++++"" project # |
6,926 | +++ ( oo / /| |goat|| ++++"" first_car_others_goat "" +++ car(( __oo oo / /| / /| / __ |goat|||goat|| ++++"" second_car_others_goat "" +++ (car( oo __oo / /|__/ /| / __ |goat|| |goat|| ++++"" third_car_others_goat "" +++ ((car oo oo __ / /| / /|__ / __ |goat|||goat|| ++++"" print('''the monty hall problemby al sweigart al@inventwithpython com in the monty hall game showyou can pick one of three doors one door has new car for prize the other two doors have worthless goats { say you pick door # before the door you choose is openedanother door with goat is opened { you can choose to either open the door you originally picked or swap to the other unopened door it may seem like it doesn' matter if you swap or notbut your odds do improve if you swap doorsthis program demonstrates the monty hall problem by letting you do repeated experiments you can read an explanation of why swapping is better at ''format(all_closedthird_goat) monty hall problem |
6,927 | swapwins swaplosses staywins staylosses while truemain program loop the computer picks which door has the car doorthathascar random randint( ask the player to pick door print(all_closed while truekeep asking the player until they enter valid door print('pick door or (or "quitto stop):' response input(''upper( if response ='quit' end the game print('thanks for playing!' sys exit( if response =' or response =' or response =' ' break doorpick int(response figure out which goat door to show the player while true select door that is goat and not picked by the player showgoatdoor random randint( if showgoatdoor !doorpick and showgoatdoor !doorthathascar break show this goat door to the player if showgoatdoor = print(first_goat elif showgoatdoor = print(second_goat elif showgoatdoor = print(third_goat print('door {contains goat!format(showgoatdoor) ask the player if they want to swap while truekeep asking until the player enters or print('do you want to swap doorsy/ ' swap input(''upper( if swap ='yor swap =' ' break swap the player' door if they wanted to swap if swap =' ' if doorpick = and showgoatdoor = doorpick elif doorpick = and showgoatdoor = doorpick project # |
6,928 | elif doorpick = and showgoatdoor = doorpick elif doorpick = and showgoatdoor = doorpick elif doorpick = and showgoatdoor = doorpick elif doorpick = and showgoatdoor = doorpick open all the doorsif doorthathascar = print(first_car_others_goatelif doorthathascar = print(second_car_others_goatelif doorthathascar = print(third_car_others_goatprint('door {has the car!format(doorthathascar)record wins and losses for swapping and not swappingif doorpick =doorthathascarprint('you won!'if swap =' 'swapwins + elif swap =' 'staywins + elseprint('sorryyou lost 'if swap =' 'swaplosses + elif swap =' 'staylosses + calculate success rate of swapping and not swappingtotalswaps swapwins swaplosses if totalswaps ! prevent zero-divide error swapsuccess round(swapwins totalswaps elseswapsuccess totalstays staywins staylosses if (staywins staylosses! prevent zero-divide staysuccess round(staywins totalstays elsestaysuccess print(print('swapping'end=''print('{wins{lossesformat(swapwinsswaplosses)end=''print('success rate {}%format(swapsuccess)print('not swapping'end=''print('{wins{lossesformat(staywinsstaylosses)end=''print('success rate {}%format(staysuccess)print(input('press enter to repeat the experiment 'monty hall problem |
6,929 | try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change doorthathascar random randint( on line to doorthathascar what happens if you replace lines to with print([first_goatsecond_goatthird_goat][showgoatdoor ]) project # |
6,930 | lt at ta this program generates multiplication table from to while simpleit provides useful demonstration of nested loops |
6,931 | when you run multiplicationtable pythe output will look like thismultiplication tableby al sweigart al@inventwithpython com --+ how it works line prints the top row of the table notice that it sets large enough distance between the numbers to accommodate products that are maximum of three digits long since this is multiplication tablethis spacing can fit the largest product if you want to create larger tableyou may need to increase the spacing for the columns as well keep in mind that the standard terminal window is columns wide and rows tallso you cannot create much larger multiplication tables without having the rows wrap around the right edge of the window """multiplication tableby al sweigart al@inventwithpython com print multiplication table view this code at tagstinybeginnermath"" print('multiplication tableby al sweigart al@inventwithpython com' print the horizontal number labels print( ' print('--+' display each row of products for number in range( ) print the vertical numbers labels print(str(number rjust( )end='' print separating bar print('|'end='' project # |
6,932 | for number in range( )print the product followed by spaceprint(str(number number rjust( )end='print(finish the row by printing newline exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change range( on line to range( ) what happens if you change range( on line to range( )multiplication table |
6,933 | yn "ninety-nine bottlesis folk song of undetermined origin known for its length and repetitiveness the lyrics go"ninetynine bottles of milk on the wallninety-nine bottles of milk take one downpass it aroundninetyeight bottles of milk on the wall as the lyrics repeatthe number of bottles falls from ninety-eight to ninetyseventhen from ninety-seven to ninety-sixuntil it reaches zero"one bottle of milk on the wallone bottle of milk take it downpass it aroundno more bottles of milk on the wall!luckily for uscomputers are excellent at performing repetitive tasksand this program reproduces all of the lyrics programmatically an extended version of this program is in project "ninety-nniine boottels |
6,934 | when you run ninetyninebottles pythe output will look like thisninety-nine bottlesby al sweigart al@inventwithpython com (press ctrl- to quit bottles of milk on the wall bottles of milktake one downpass it around bottles of milk on the wall bottles of milk on the wall bottles of milktake one downpass it around bottles of milk on the wall--snip-how it works the repetition in this song makes it easy to use for loop (from lines to to display the first stanzas howeverthe last stanza has some minor differences and requires separate code to display (lines to this is because the last line'no more bottles of milk on the wall!'deviates from the line repeated in the loopand because the word "bottleis singular rather than plural """ninety-nine bottles of milk on the wall by al sweigart al@inventwithpython com print the full lyrics to one of the longest songs everpress ctrl- to stop view this code at tagstinybeginnerscrolling"" import systime print('ninety-nine bottlesby al sweigart al@inventwithpython com' print( print('(press ctrl- to quit )' time sleep( bottles this is the starting number of bottles pause (!try changing this to to see the full song at once try while bottles keep looping and display the lyrics print(bottles'bottles of milk on the wall,' time sleep(pausepause for pause number of seconds print(bottles'bottles of milk,' time sleep(pause print('take one downpass it around,' time sleep(pauseninety-nine bottles |
6,935 | bottles bottles decrease the number of bottles by one print(bottles'bottles of milk on the wall!' time sleep(pause print(print newline display the last stanza print(' bottle of milk on the wall,' time sleep(pause print(' bottle of milk,' time sleep(pause print('take it downpass it around,' time sleep(pause print('no more bottles of milk on the wall!' except keyboardinterrupt sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingcreate program for the repetitive song "the twelve days of christmas create programs for other cumulative songs you can find list of them at exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change bottles bottles on line to bottles bottles what happens if you change while bottles on line to while bottles : project # |
6,936 | yn in this version of the song "ninety-nine bottles,the program introduces small imperfections in each stanza by either removing letterswapping the casing of lettertransposing two lettersor doubling letter as the song continues to playthese mutations add upresulting in very silly song it' good idea to try project "ninety-nine bottles,before attempting this one |
6,937 | when you run ninetyninebottles pythe output will look like thisninety-nniine boottelsby al sweigart al@inventwithpython com --snip- bottles of milk on the wall bottles of milktake one downpass it around bottles of milk on the wall bottles of milk on the wall bottles of milktake one wnpass it around bottles of milk on the wall bottles of milk on the wall bottels of milktake one wnpass it around bottles of milk on the wall--snip- otlte of mil on teh wall ottels milktake one wnpass it ar und bbottles of milk on wall--snip- otle of iml oo nteh lall tle ff fmmliikktaake on wnpaasss itt au nn dno more bottles of milk on the wallhow it works string values in python are immutablemeaning they cannot be changed if the string 'hellois stored in variable called greetingthe code greeting greeting world!doesn' actually change the 'hellostring ratherit creates new string'hello world!'to replace the 'hellostring in reeting the technical reasons for this are beyond the scope of this bookbut it' important to understand the distinctionbecause it means code like reeting[ 'hisn' allowedsince strings are immutable howeversince lists are mutablewe can create list of single-character strings (as line does)change the characters in the listand then create string from the list (line this is how our program seemingly changesor mutatesthe strings containing the song lyrics """ninety-nniine boottels of mlik on teh wall by al sweigart al@inventwithpython com print the full lyrics to one of the longest songs everthe song gets sillier and sillier with each verse press ctrl- to stop view this code at tagsshortscrollingword"" project # |
6,938 | set up the constants (!try changing both of these to to print all the lyrics at once speed the pause in between printing letters line_pause the pause at the end of each line def slowprint(textpauseamount= ) """slowly print out the characters in text one at time "" for character in text set flush=true here so the text is immediately printed print(characterflush=trueend=''end='means no newline time sleep(pauseamountpause in between each character print(print newline print('ninety-nniine boottelsby al sweigart al@inventwithpython com' print( print('(press ctrl- to quit )' time sleep( bottles this is the starting number of bottles this list holds the string used for the lyrics lines [bottles of milk on the wall,' bottles of milk,' 'take one downpass it around,' bottles of milk on the wall!' try while bottles keep looping and display the lyrics slowprint(str(bottleslines[ ]speed time sleep(line_pause slowprint(str(bottleslines[ ]speed time sleep(line_pause slowprint(lines[ ]speed time sleep(line_pause bottles bottles decrease the number of bottles by one if bottles print the last line of the current stanza slowprint(str(bottleslines[ ]speed elseprint the last line of the entire song slowprint('no more bottles of milk on the wall!'speed time sleep(line_pause print(print newline choose random line to make "sillier" linenum random randint( make list from the line string so we can edit it (strings in python are immutable line list(lines[linenum]ninety-nniine boottels |
6,939 | effect random randint( if effect = replace character with space charindex random randint( len(line line[charindex elif effect = change the casing of character charindex random randint( len(line if line[charindexisupper() line[charindexline[charindexlower( elif line[charindexislower() line[charindexline[charindexupper( elif effect = transpose two characters charindex random randint( len(line firstchar line[charindex secondchar line[charindex line[charindexsecondchar line[charindex firstchar elif effect = double character charindex random randint( len(line line insert(charindexline[charindex] convert the line list back to string and put it in lines lines[linenum'join(line except keyboardinterrupt sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingswap the order of two adjacent wordswhere "wordis text separated by spaces on rare occasionshave the song start counting upward for few iterations change the case of an entire word exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change bottles bottles on line to bottles bottles what happens if you change effect random randint( on line to effect what error happens if you delete or comment out line list(lines [linenum]on line project # |
6,940 | numer al system counters we're used to counting in the decimal numeral systemwhich uses digits through this system likely developed because humans counted on their fingersand most people have fingers but other number systems exist computers make use of binarya numeral system with only two digits and programmers also sometimes use hexadecimalwhich is base- numeral system that uses the digits to but also extends into the letters to we can represent any number in any numeral systemand this program displays range of numbers in decimalbinaryand hexadecimal |
6,941 | when you run numeralsystems pythe output will look like thisnumeral system countersby al sweigart al@inventwithpython com --snip-enter the starting number ( enter how many numbers to display ( dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hexa bin dec hexb bin dec hexc bin dec hexd bin dec hexe bin dec hexf bin dec hex bin dec hex bin dec hex bin dec hex bin how it works you can get the binary and hexadecimal representations of number in python by calling the bin(and hex(functionsrespectivelybin( ' hex( ' aconvert these strings back into decimal integers by calling int(and supplying the base to convert fromlike soint(' ' int(' ' keep in mind that the binary and hexadecimal "numbersreturned by bin(and hex(are actually string valuesbin( returns the string ' and hex( returns the string ' ain programmingit is convention to add prefix to binary numbers and prefix to hexadecimal numbers project # |
6,942 | decimalwith the decimal number "ten thousand the numeral systems program removes these prefixes before displaying the number """numeral system countersby al sweigart al@inventwithpython com shows equivalent numbers in decimalhexadecimaland binary view this code at tagstinymath"" print('''numeral system countersby al sweigart al@inventwithpython com this program shows you equivalent numbers in decimal (base ) hexadecimal (base )and binary (base numeral systems (ctrl- to quit ''' while true response input('enter the starting number ( ' if response ='' response ' start at by default break if response isdecimal() break print('please enter number greater than or equal to ' start int(response while true response input('enter how many numbers to display ( ' if response ='' response ' display numbers by default break if response isdecimal() break print('please enter number ' amount int(response for number in range(startstart amount)main program loop convert to hexadecimal/binary and remove the prefix hexnumber hex(number)[ :upper( binnumber bin(number)[ : print('dec:'numberhex:'hexnumberbin:'binnumberafter entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingenter new row for octalthe base- number systemusing python' oct(function search the internet for "number system conversionto find out how to implement your own bin()oct()and hex(functions numeral system counters |
6,943 | try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change hex(number)[ :upper(on line to hex(number)[ :] what error do you cause if you change int(responseon line to response project # |
6,944 | ta the elements the periodic table of the elements organizes all known chemical elements into single table this program presents this table and lets the player access additional information about each elementsuch as its atomic numbersymbolmelting pointand so on compiled this information from wikipedia and stored it in file called periodictable csv that you can download from |
6,945 | when you run periodictable pythe output will look like thisperiodic table of elements by al sweigart al@inventwithpython com periodic table of elements he li be ne na mg al si cl ar ca sc ti cr mn fe co ni cu zn ga ge as se br kr rb sr zr nb mo tc ru rh pd ag cd in sn sb te xe cs ba la hf ta re os ir pt au hg tl pb bi po at rn fr ra ac rf db sg bh hs mt ds rg cn nh fl mc lv ts og ce pr nd pm sm eu gd tb dy ho er tm yb lu th pa np pu am cm bk cf es fm md no lr enter symbol or atomic number to examineor quit to quit atomic number symbolmo elementmolybdenum origin of namegreek molybdaina'piece of lead'from molybdos'leadgroup period atomic weight ( density /cm^ melting point boiling point specific heat capacity /( *kelectronegativity abundance in earth' crust mg/kg press enter to continue --snip-how it works csvor comma-separated valuesfile is text file that represents primitive spreadsheet each line in the csv file is rowand commas separate the columns for examplethe first three lines in periodictable csv look like this , ,hydrogen,"greek elements hydroand -genmeaning 'water-forming--snip- ,he,helium,"greek helios'sun'", , , ( )[iii][ ], --snip- ,li,lithium,"greek lithos'stone'", , , [iii][iv][ ][viii][vi],--snip-python' csv module makes it easy to import data from csv file and into list of lists of stringsas lines to do lines to turn this list of lists into dictionary so that the rest of the program can easily summon the information by an element' name or atomic number project # |
6,946 | displays atomic information for all the elements view this code at tagsshortscience"" data from highlight the tablecopy itthen paste it into spreadsheet program like excel or google sheets like in then save this file as periodictable csv or download this csv file from import csvsysre read in all the data from periodictable csv elementsfile open('periodictable csv'encoding='utf- ' elementscsvreader csv reader(elementsfile elements list(elementscsvreader elementsfile close( all_columns ['atomic number''symbol''element''origin of name' 'group''period''atomic weight''density' 'melting point''boiling point' 'specific heat capacity''electronegativity' 'abundance in earth\' crust' to justify the textwe need to find the longest string in all_columns longest_column for key in all_columns if len(keylongest_column longest_column len(key put all the elements data into data structure elements {the data structure that stores all the element data for line in elements element {'atomic number'line[ ] 'symbol'line[ ] 'element'line[ ] 'origin of name'line[ ] 'group'line[ ] 'period'line[ ] 'atomic weight'line[ 'atomic mass unit 'density'line[ /cm^ 'grams/cubic cm 'melting point'line[ 'kelvin 'boiling point'line[ 'kelvin 'specific heat capacity'line[ /( * )' 'electronegativity'line[ ] 'abundance in earth\' crust'line[ mg/kg' some of the data has bracketed text from wikipedia that we want to removesuch as the atomic weight of boron " [iii][iv][ ][vi]should be " for keyvalue in element items() remove the [roman numeraltextperiodic table of the elements |
6,947 | element[keyre sub( '\[( | | )+\]'''value elements[line[ ]element map the atomic number to the element elements[line[ ]element map the symbol to the element print('periodic table of elements' print('by al sweigart al@inventwithpython com' print( while truemain program loop show table and let the user select an element print(''periodic table of elements he li be ne na mg al si cl ar ca sc ti cr mn fe co ni cu zn ga ge as se br kr rb sr zr nb mo tc ru rh pd ag cd in sn sb te xe cs ba la hf ta re os ir pt au hg tl pb bi po at rn fr ra ac rf db sg bh hs mt ds rg cn nh fl mc lv ts og ce pr nd pm sm eu gd tb dy ho er tm yb lu th pa np pu am cm bk cf es fm md no lr''' print('enter symbol or atomic number to examineor quit to quit ' response input(''title( if response ='quit' sys exit( display the selected element' data if response in elements for key in all_columns keyjustified key rjust(longest_column print(keyjustified 'elements[response][key] input('press enter to continue 'exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what bug do you cause if you change response ='quiton line to response ='quit' what happens if you delete or comment out lines and project # |
6,948 | at pig latin is word game that transforms english words into parody of latin in pig latinif word begins with consonantthe speaker removes this letter and puts it at the endfollowed by "ay for example"pigbecomes "igpayand "latinbecomes "atinlay otherwiseif the word begins with vowelthe speaker simply adds "yayto the end of it for example"elephantbecomes "elephantyayand "umbrellabecomes "umbrellayay |
6,949 | when you run piglatin pythe output will look like thisigpay atinlay (pig latinby al sweigart al@inventwithpython com enter your messagethis is very serious message isthay isyay ayay eryvay erioussay essagemay (copied pig latin to clipboard how it works the englishtopiglatin(function takes string of english text and returns string of its pig latin equivalent the main(function only gets called if user runs the program directly you could also write your own python programsimport piglatin py with an import piglatin statementthen call iglatin englishtopiglatin(to make use of the englishtopiglatin(function this reuse technique can save you the time and effort required to reinvent this code yourself """pig latinby al sweigart al@inventwithpython com translates english messages into igpay atinlay view this code at tagsshortword"" try import pyperclip pyperclip copies text to the clipboard except importerror pass if pyperclip is not installeddo nothing it' no big deal vowels (' '' '' '' '' '' ' def main() print('''igpay atinlay (pig latin by al sweigart al@inventwithpython com enter your message:''' piglatin englishtopiglatin(input('') join all the words back together into single string print(piglatin try pyperclip copy(piglatin print('(copied pig latin to clipboard )' except nameerror pass do nothing if pyperclip wasn' installed project # |
6,950 | def englishtopiglatin(message) piglatin ' string of the pig latin translation for word in message split() separate the non-letters at the start of this word prefixnonletters ' while len(word and not word[ isalpha() prefixnonletters +word[ word word[ : if len(word= piglatin piglatin prefixnonletters continue separate the non-letters at the end of this word suffixnonletters ' while not word[- isalpha() suffixnonletters word[- suffixnonletters word word[:- remember if the word was in uppercase or titlecase wasupper word isupper( wastitle word istitle( word word lower(make the word lowercase for translation separate the consonants at the start of this word prefixconsonants ' while len(word and not word[ in vowels prefixconsonants +word[ word word[ : add the pig latin ending to the word if prefixconsonants !'' word +prefixconsonants 'ay else word +'yay set the word back to uppercase or titlecase if wasupper word word upper( if wastitle word word title( add the non-letters back to the start or end of the word piglatin +prefixnonletters word suffixnonletters return piglatin if __name__ ='__main__' main(pig latin |
6,951 | try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change message split(on line to message what happens if you change (' '' '' '' '' '' 'on line to () what happens if you change (' '' '' '' '' '' 'on line to (' '' '' '' '' '' ') project # |
6,952 | pow erball lot tery the powerball lottery is an exciting way to lose small amounts of money if you purchase $ ticketyou can pick six numbersfive drawn from to and sixth "powerballnumber drawn from to the order of the numbers doesn' matter if the lottery selects your six numbersyou win $ billion dollarsexcept you won' winbecause your odds are in , , but if you spent $ on ticketsyour odds would be in , , you won' win that eitherbut at least you'll lose times as much money the more you like losing moneythe more fun the lottery isto help you visualize how often you won' win the lotterythis program simulates up to one million powerball drawings and then compares them with the numbers you picked now you can have all the excitement of losing the lottery without spending money |
6,953 | the next time you want to buy lottery ticketpick the numbers and those numbers are just as likely to come up as more complex set the program in action when you run powerballlottery pythe output will look like thispowerball lotteryby al sweigart al@inventwithpython com each powerball lottery ticket costs $ the jackpot for this game is $ billionit doesn' matter what the jackpot isthoughbecause the odds are in , , so you won' win this simulation gives you the thrill of playing without wasting money enter different numbers from to with spaces between each number (for example enter the powerball number from to how many times do you want to play(max it costs $ to play timesbut don' worry ' sure you'll win it all back press enter to start the winning numbers are and you lost the winning numbers are and you lost the winning numbers are and you lost --snip-the winning numbers are and you lost the winning numbers are and you lost the winning numbers are and you lost you have wasted $ thanks for playinghow it works the output from this program looks fairly uniform because the allwinning nums ljust( code on line pads the numbers with enough spaces to take up columnsno matter how many digits the winning numbers have this makes the "you lost text always appear in the same place on the screenso it remains readable even as the program quickly outputs several lines """powerball lotteryby al sweigart al@inventwithpython com simulation of the lottery so you can experience the thrill of losing the lottery without wasting your money view this code at tagsshorthumorsimulation"" project # |
6,954 | print('''powerball lotteryby al sweigart al@inventwithpython com each powerball lottery ticket costs $ the jackpot for this game is $ billionit doesn' matter what the jackpot isthough because the odds are in , , so you won' win this simulation gives you the thrill of playing without wasting money ''' let the player enter the first five numbers to while true print('enter different numbers from to with spaces between' print('each number (for example )' response input('' check that the player entered things numbers response split( if len(numbers! print('please enter numbersseparated by spaces ' continue convert the strings into integers try for in range( ) numbers[iint(numbers[ ] except valueerror print('please enter numberslike or ' continue check that the numbers are between and for in range( ) if not ( <numbers[ < ) print('the numbers must all be between and ' continue check that the numbers are unique (create set from number to remove duplicates if len(set(numbers)! print('you must enter different numbers ' continue break let the player select the powerball to while true print('enter the powerball number from to ' response input('' convert the strings into integers try powerball int(response except valueerror print('please enter numberlike or 'powerball lottery |
6,955 | continue check that the number is between and if not ( <powerball < ) print('the powerball number must be between and ' continue break enter the number of times you want to play while true print('how many times do you want to play(max )' response input('' convert the strings into integers try numplays int(response except valueerror print('please enter numberlike or ' continue check that the number is between and if not ( <numplays < ) print('you can play between and times ' continue break run the simulation price '$str( numplays print('it costs'price'to play'numplays'timesbut don\' ' print('worry \' sure you\'ll win it all back ' input('press enter to start ' possiblenumbers list(range( ) for in range(numplays) come up with lottery numbers random shuffle(possiblenumbers winningnumbers possiblenumbers[ : winningpowerball random randint( display winning numbers print('the winning numbers are'end='' allwinningnums ' for in range( ) allwinningnums +str(winningnumbers[ ] allwinningnums +'and str(winningpowerball print(allwinningnums ljust( )end='' notesets are not orderedso it doesn' matter what order the integers in set(numbersand set(winningnumbersare if (set(numbers=set(winningnumbers and powerball =winningpowerball) print( print('you have won the powerball lotterycongratulations,' project # |
6,956 | print('you would be billionaire if this was real!' break else print(you lost 'the leading space is required here print('you have wasted'price print('thanks for playing!'exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change possiblenumbers[ : on line to numbers and random randint( on line to powerball what error do you get if you delete or comment out possiblenumbers list(range( )on line powerball lottery |
6,957 | prime numbers prime number is number that is evenly divisible only by one and itself prime numbers have variety of practical applicationsbut no algorithm can predict themwe must calculate them one at time howeverwe do know that there is an infinite number of prime numbers to be discovered this program finds prime numbers through brute-force calculation its code is similar to project "factor finder (another way to describe prime number is that one and the number itself are its only factors you can find out more about prime numbers from prime_number |
6,958 | when you run primenumbers pythe output will look like thisprime numbersby al sweigart al@inventwithpython com --snip-enter number to start searching for primes from(try or ( zerosor another number press ctrl- at any time to quit press enter to begin --snip-how it works the isprime(function accepts an integer and returns true if it is prime number otherwiseit returns false project is worth studying if you're trying to understand this program the isprime(function essentially looks for any factors in the given number and returns false if it finds any the algorithm in this program can quickly find large prime numbers the number one trillion has mere digits but to find prime numbers that are as big as googol ( one followed by zeros)you need to use an advanced algorithm such as the rabin-miller primality test of my book cracking codes with python (no starch press has python implementation of this algorithm """prime numbersby al sweigart al@inventwithpython com calculates prime numberswhich are numbers that are only evenly divisible by one and themselves they are used in variety of practical applications more info at view this code at tagstinymathscrolling"" import mathsys def main() print('prime numbersby al sweigart al@inventwithpython com' print('prime numbers are numbers that are only evenly divisible by' print('one and themselves they are used in variety of practical' print('applicationsbut cannot be predicted they must be' print('calculated one at time ' print( while true print('enter number to start searching for primes from:' print('(try or ( zerosor another number )'prime numbers |
6,959 | response input('' if response isdecimal() num int(response break input('press ctrl- at any time to quit press enter to begin ' while true print out any prime numbers if isprime(num) print(str(num''end=''flush=true num num go to the next number def isprime(number) """returns true if number is primeotherwise returns false "" handle special cases if number return false elif number = return true try to evenly divide number by all numbers from up to number' square root for in range( int(math sqrt(number) ) if number = return false return true if this program was run (instead of imported)run the game if __name__ ='__main__' try main( except keyboardinterrupt sys exit(when ctrl- is pressedend the program exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what error do you get if you change response isdecimal(on line to response and enter non-number for the number from which to start searching for primes what happens if you change number what happens if you change number = on line to number ! project # |
6,960 | progress bar progress bar is visual element that shows how much of task has been completed progress bars are often used alongside downloading files or software installations this project creates getprogressbar(function that returns progress bar string based on the arguments passed to it it simulates downloading filebut you can reuse the progress bar code in your own projects |
6,961 | when you run progressbar pythe output will look like thisprogress bar simulationby al sweigart [######## / how it works the progress bar relies on certain trick that programs running in terminal windows can perform just as '\nand '\tare escape characters for newline and tab charactersrespectively'\bis an escape character for backspace characters if you "printa backspace characterthe text cursor will move to the left and erase the previously printed character this only works for the current line the text cursor is on if you run the code print('hello\ \ \ \ \bhowdy')python will print the text "hello,move the text cursor back five spacesand then print the text "howdy the "howdytext will overwrite "hello,making it look as though you called "howdy we can use this technique to create an animated progress bar on single line by printing one version of the barmoving the text cursor back to the startthen printing an updated progress bar this effect can generate any text animation without requiring module such as bextthough it will be limited to taking up single line in the terminal window once you've created this programyou can display progress bars in your other python programs by running import progressbar and printing the string returned from progressbar getprogressbar( """progress bar simulationby al sweigart al@inventwithpython com sample progress bar animation that can be used in other programs view this code at tagstinymodule"" import randomtime bar chr( character is '# def main() simulate download print('progress bar simulationby al sweigart' bytesdownloaded downloadsize while bytesdownloaded downloadsize "downloada random amount of "bytes" bytesdownloaded +random randint( get the progress bar string for this amount of progress barstr getprogressbar(bytesdownloadeddownloadsize don' print newline at the endand immediately flush the printed string to the screen print(barstrend=''flush=true project # |
6,962 | time sleep( pause for little bit print backspaces to move the text cursor to the line' start print('\blen(barstr)end=''flush=true def getprogressbar(progresstotalbarwidth= ) """returns string that represents progress bar that has barwidth bars and has progressed progress amount out of total amount "" progressbar 'the progress bar will be string value progressbar +'[create the left end of the progress bar make sure that the amount of progress is between and total if progress total progress total if progress progress calculate the number of "barsto display numberofbars int((progress totalbarwidth progressbar +bar numberofbars add the progress bar progressbar +(barwidth numberofbarsadd empty space progressbar +']add the right end of the progress bar calculate the percentage complete percentcomplete round(progress total progressbar +str(percentcomplete'%add percentage add the numbers progressbar +str(progress'/str(total return progressbar return the progress bar string if the program is run (instead of imported)run the game if __name__ ='__main__' main(after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingcreate one-line animation of spinner that alternates between the characters |/-and to produce rotating effect create program that can display scrolling marquee of text moving from left to right create one-line animation that displays set of four equal signs moving back and forth as single unitsimilar to the red scanning light on the robot car from the tv show knight rider or the cylon robot face from the tv show battlestar galactica progress bar |
6,963 | try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you delete or comment out print('\blen(barstr)end=''flush=trueon line what happens if you switch the order of lines and what happens if you change round(progress total on line to round(progress total ) project # |
6,964 | ainbow rainbow is simple program that shows colorful rainbow traveling back and forth across the screen the program makes use of the fact that when new lines of text appearthe existing text scrolls upcausing it to look like it' moving this program is good for beginnersand it' similar to project "deep cave |
6,965 | figure - shows what the output will look like when you run rainbow py figure - the zigzag output of the rainbowwhich is in color on the screen how it works this program continuously prints the same rainbow pattern what changes is the number of space characters printed to the left of it increasing this number moves the rainbow to the rightand decreasing it moves the rainbow to the left the indent variable keeps track of the number of spaces the indentincreasing variable is set to true to note that indent should increase until it reaches at which point it changes to false the rest of the code decreases the number of spaces once it reaches it changes back to true again to repeat the zigzag of the rainbow """rainbowby al sweigart al@inventwithpython com shows simple rainbow animation press ctrl- to stop view this code at tagstinyartisticbextbeginnerscrolling"" import timesys try import bext except importerror print('this program requires the bext modulewhich you' print('can install by following the instructions at' print(' sys exit( project # |
6,966 | print('rainbowby al sweigart al@inventwithpython com' print('press ctrl- to stop ' time sleep( indent how many spaces to indent indentincreasing true whether the indentation is increasing or not try while truemain program loop print(indentend='' bext fg('red' print('##'end='' bext fg('yellow' print('##'end='' bext fg('green' print('##'end='' bext fg('blue' print('##'end='' bext fg('cyan' print('##'end='' bext fg('purple' print('##' if indentincreasing increase the number of spaces indent indent if indent = (!change this to or change direction indentincreasing false else decrease the number of spaces indent indent if indent = change direction indentincreasing true time sleep( add slight pause except keyboardinterrupt sys exit(when ctrl- is pressedend the program exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change false on line to true what happens if you change the argument to all bext fg(calls to 'random'rainbow |
6,967 | ro pa sc so in this version of the two-player hand game also known as rochambeau or jan-ken-ponthe player faces off against the computer you can pick either rockpaperor scissors rock beats scissorsscissors beats paperand paper beats rock this program adds some brief pauses for suspense for variation of this gamesee project "rock paper scissors (always-win version |
6,968 | when you run rockpaperscissors pythe output will look like thisrockpaperscissorsby al sweigart al@inventwithpython com rock beats scissors paper beats rocks scissors beats paper wins losses ties enter your move( )ock ( )aper ( )cissors or ( )uit rock versus scissors you win wins losses ties enter your move( )ock ( )aper ( )cissors or ( )uit --snip-how it works the game logic for rock paper scissors is fairly straightforwardand we implement it here with ifelif statements to add bit of suspenselines to count down before revealing the opponent' movewith brief pauses between counts this gives the player period in which their excitement builds about the results of the game without this pausethe results would appear as soon as the player entered their move-- bit anticlimactic it doesn' take lot of code to improve the user experience for the player """rockpaperscissorsby al sweigart al@inventwithpython com the classic hand game of luck view this code at tagsshortgame"" import randomtimesys print('''rockpaperscissorsby al sweigart al@inventwithpython com rock beats scissors paper beats rocks scissors beats paper ''' these variables keep track of the number of winslossesand ties wins losses ties while truemain game loop while truekeep asking until player enters rpsor print('{wins{losses{tiesformat(winslossesties)rock paper scissors |
6,969 | project # print('enter your move( )ock ( )aper ( )cissors or ( )uit'playermove input(''upper(if playermove =' 'print('thanks for playing!'sys exit(if playermove ='ror playermove ='por playermove =' 'break elseprint('type one of rpsor 'display what the player choseif playermove =' 'print('rock versus 'playermove 'rockelif playermove =' 'print('paper versus 'playermove 'paperelif playermove =' 'print('scissors versus 'playermove 'scissorscount to three with dramatic pausestime sleep( print(' 'time sleep( print(' 'time sleep( print(' 'time sleep( display what the computer choserandomnumber random randint( if randomnumber = computermove 'rockelif randomnumber = computermove 'paperelif randomnumber = computermove 'scissorsprint(computermovetime sleep( display and record the win/loss/tieif playermove =computermoveprint('it\' tie!'ties ties elif playermove ='rockand computermove ='scissors'print('you win!'wins wins elif playermove ='paperand computermove ='rock'print('you win!'wins wins elif playermove ='scissorsand computermove ='paper'print('you win!'wins wins |
6,970 | elif playermove ='rockand computermove ='paper'print('you lose!'losses losses elif playermove ='paperand computermove ='scissors'print('you lose!'losses losses elif playermove ='scissorsand computermove ='rock'print('you lose!'losses losses after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingadd "lizardand "spockmoves to the game lizard poisons spock and eats paperbut is crushed by rock and decapitated by scissors spock breaks scissors and vaporizes rockbut is poisoned by lizard and disproved by paper allow the player to win point for each victory and lose point for each defeat upon winningthe player can also take "double or nothingrisks to possibly win and an increasing number of points in subsequent rounds exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what error do you get if you change random randint( on line to random randint( ) what happens if you change playermove =computermove on line to truerock paper scissors |
6,971 | ro pa sc so ay this variant of rock paper scissors is identical to project "rock paper scissors,except the player will always win the code selecting the computer' move is set so that it always chooses the losing move you can offer this game to your friendswho may be excited when they win at first see how long it takes before they catch on to the fact that the game is rigged in their favor |
6,972 | when you run rockpaperscissorsalwayswin pythe output will look like thisrockpaperscissorsby al sweigart al@inventwithpython com rock beats scissors paper beats rocks scissors beats paper wins losses ties enter your move( )ock ( )aper ( )cissors or ( )uit paper versus rock you win wins losses ties enter your move( )ock ( )aper ( )cissors or ( )uit scissors versus paper you win wins losses ties --snip-scissors versus paper you win wins losses ties enter your move( )ock ( )aper ( )cissors or ( )uit --snip-how it works you may notice that this version of the program is shorter than project this makes sensewhen you don' have to randomly generate move for the computer and compute the results of the gameyou can remove quite bit of code from the original there are also no variables to track the number of losses and tiessince these would be zero all the time anyway """rockpaperscissors (always win version by al sweigart al@inventwithpython com the classic hand game of luckexcept you always win view this code at tagstinygamehumor"" rock paper scissors (always-win version |
6,973 | print('''rockpaperscissorsby al sweigart al@inventwithpython com rock beats scissors paper beats rocks scissors beats paper ''' these variables keep track of the number of wins wins while truemain game loop while truekeep asking until player enters rpsor print('{wins losses tiesformat(wins) print('enter your move( )ock ( )aper ( )cissors or ( )uit' playermove input(''upper( if playermove =' ' print('thanks for playing!' sys exit( if playermove ='ror playermove ='por playermove =' ' break else print('type one of rpsor ' display what the player chose if playermove =' ' print('rock versus ' elif playermove =' ' print('paper versus ' elif playermove =' ' print('scissors versus ' count to three with dramatic pauses time sleep( print(' ' time sleep( print(' ' time sleep( print(' ' time sleep( display what the computer chose if playermove =' ' print('scissors' elif playermove =' ' print('rock' elif playermove =' ' print('paper' time sleep( print('you win!' wins wins project # |
6,974 | experimental changes to it on your ownyou can also try to figure out how to do the followingadd "lizardand "spockmoves to the game lizard poisons spock and eats paperbut is crushed by rock and decapitated by scissors spock breaks scissors and vaporizes rockbut is poisoned by lizard and disproved by paper allow the player to win point for each victory upon winningthe player can also take "double or nothingrisks to possibly win and an increasing number of points exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you delete or comment out lines to what happens if you change input(''upper(on line to input('')rock paper scissors (always-win version |
6,975 | rot cipher the rot cipherone of the simplest encryption algorithmsstands for "rotate spaces the cypher represents the letters to as the numbers to in such way that the encrypted letter is spaces from the plaintext lettera becomes nb becomes oand so on the encryption process is identical to the decryption processmaking it trivial to program howeverthe encryption is also trivial to break because of thisyou'll most often find rot used to conceal non-sensitive informationsuch as spoilers or trivia answersso it' not read unintentionally more information about the rot cipher can be found at wiki/rot if you' like to learn about ciphers and code breaking more generallyyou can read my book cracking codes with python (no starch press |
6,976 | when you run rot cipher pythe output will look like thisrot cipherby al sweigart al@inventwithpython com enter message to encrypt/decrypt (or quit)meet me by the rose bushes tonight the translated message iszrrg zr ol gur ebfr ohfurf gbavtug (copied to clipboard enter message to encrypt/decrypt (or quit)--snip-how it works rot shares lot of code with project "caesar cipher,although it' much simpler because it always uses the key since the same code performs both the encryption and decryption (lines to )there' no need to ask the player which mode they want to use one difference is that this program maintains the casing of the original message instead of automatically converting the message to uppercase for example"helloencrypts to "uryyb,whereas "helloencrypts to "ury yb """rot cipherby al sweigart al@inventwithpython com the simplest shift cipher for encrypting and decrypting text more info at view this code at tagstinycryptography"" try import pyperclip pyperclip copies text to the clipboard except importerror pass if pyperclip is not installeddo nothing it' no big deal set up the constants upper_letters 'abcdefghijklmnopqrstuvwxyz lower_letters 'abcdefghijklmnopqrstuvwxyz print('rot cipherby al sweigart al@inventwithpython com' print( while truemain program loop print('enter message to encrypt/decrypt (or quit):' message input('' if message upper(='quit' break break out of the main program loop rotate the letters in message by characters rot cipher |
6,977 | translated 'for character in messageif character isupper()concatenate uppercase translated character transcharindex (upper_letters find(character translated +upper_letters[transcharindexelif character islower()concatenate lowercase translated character transcharindex (lower_letters find(character translated +lower_letters[transcharindexelseconcatenate the character untranslated translated +character display the translationprint('the translated message is:'print(translatedprint(trycopy the translation to the clipboardpyperclip copy(translatedprint('(copied to clipboard )'exceptpass exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change character isupper(on line to character islower() what happens if you change print(translatedon line to print(message) project # |
6,978 | tat this project features an animation of cube rotating using trigonometric functions you can adapt the point rotation math and the line(function in your own animation programs although the block text characters we'll use to draw the cube don' look like thinstraight linesthis kind of drawing is called wireframe model because it renders only the edges of an object' surfaces figure - shows the wireframe model for cube and an icospherea rough sphere made of triangles |
6,979 | the program in action figure - shows what the output will look like when you run rotatingcube py figure - the wireframe cube that the program draws to the screen project # |
6,980 | this algorithm has two main partsthe line(function and the rotatepoint(function the cube has eight pointsone for each corner the program stores these corners as (xyztuples in the cube_corners list these points also define the connections for the cube' edge lines when all the points rotate in the same direction by the same amountthey give the illusion of cube rotating """rotating cubeby al sweigart al@inventwithpython com rotating cube animation press ctrl- to stop view this code at tagslargeartisticmath"" this program must be run in terminal/command prompt window import mathtimesysos set up the constants pause_amount pause length of one-tenth of second widthheight scalex (width / scaley (height / text cells are twice as tall as they are wideso set scaley scaley * translatex (width / translatey (height / (!try changing this to '#or '*or some other character line_char chr( character is '# (!try setting two of these values to zero to rotate the cube only along single axis x_rotate_speed y_rotate_speed z_rotate_speed this program stores xyz coordinates in listswith the coordinate at index at and at these constants make our code more readable when accessing the coordinates in these lists def line( ) """returns list of points in line between the given points uses the bresenham line algorithm more info at points [contains the points of the line "steepmeans the slope of the line is greater than degrees or less than - degrees rotating cube |
6,981 | project # check for the special case where the start and end points are certain neighborswhich this function doesn' handle correctlyand return hard coded list insteadif ( = and = or ( = and = )return [( )( )issteep abs( abs( if issteepthis algorithm only handles non-steep linesso let' change the slope to non-steep and change it back later swap and swap and isreversed true if the line goes right-to-left if isreversedget the points on the line going right-to-left swap and swap and deltax deltay abs( extray int(deltax currenty if ydirection elseydirection - calculate the for every in this linefor currentx in range( - )if issteeppoints append((currentycurrentx)elsepoints append((currentxcurrenty)extray -deltay if extray < only change once extray < currenty -ydirection extray +deltax elseget the points on the line going left to right deltax deltay abs( extray int(deltax currenty if ydirection elseydirection - calculate the for every in this linefor currentx in range( )if issteeppoints append((currentycurrentx)elsepoints append((currentxcurrenty)extray -deltay if extray only change once extray currenty +ydirection extray +deltax |
6,982 | return points def rotatepoint(xyzaxayaz) """returns an (xyztuple of the xyz arguments rotated the rotation happens around the origin by angles axayaz (in radians directions of each axis - +-+ + "" rotate around axis rotatedx rotatedy ( math cos(ax)( math sin(ax) rotatedz ( math sin(ax)( math cos(ax) xyz rotatedxrotatedyrotatedz rotate around axis rotatedx ( math sin(ay)( math cos(ay) rotatedy rotatedz ( math cos(ay)( math sin(ay) xyz rotatedxrotatedyrotatedz rotate around axis rotatedx ( math cos(az)( math sin(az) rotatedy ( math sin(az)( math cos(az) rotatedz return (rotatedxrotatedyrotatedz def adjustpoint(point) """adjusts the xyz point to xy point fit for displaying on the screen this resizes this point by scale of scalex and scaleythen moves the point by translatex and translatey "" return (int(point[xscalex translatex) int(point[yscaley translatey) """cube_corners stores the xyz coordinates of the corners of cube the indexes for each corner in cube_corners are marked in this diagram --- // --- -|- || --- "" cube_corners [[- - - ]point - - ]point [- - ]point rotating cube |
6,983 | - ]point [- - ]point - ]point [- ]point ]point rotatedcorners stores the xyz coordinates from cube_corners after they've been rotated by rxryand rz amounts rotatedcorners [nonenonenonenonenonenonenonenone rotation amounts for each axis xrotation yrotation zrotation try while truemain program loop rotate the cube along different axes by different amounts xrotation +x_rotate_speed yrotation +y_rotate_speed zrotation +z_rotate_speed for in range(len(cube_corners)) cube_corners[ ][ cube_corners[ ][ cube_corners[ ][ rotatedcorners[irotatepoint(xyzxrotation yrotationzrotation get the points of the cube lines cubepoints [ for fromcornerindextocornerindex in (( )( )( )( )( )( )( )( )( )( )( )( )) fromxfromy adjustpoint(rotatedcorners[fromcornerindex] toxtoy adjustpoint(rotatedcorners[tocornerindex] pointsonline line(fromxfromytoxtoy cubepoints extend(pointsonline get rid of duplicate points cubepoints tuple(frozenset(cubepoints) display the cube on the screen for in range(height) for in range(width) if (xyin cubepoints display full block print(line_charend=''flush=false else display empty space print('end=''flush=false print(flush=false print('press ctrl- to quit 'end=''flush=true time sleep(pause_amountpause for bit clear the screen if sys platform ='win ' project # |
6,984 | os system('cls'windows uses the cls command else os system('clear'macos and linux use the clear command except keyboardinterrupt print('rotating cubeby al sweigart al@inventwithpython com' sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingmodify cube_corners and the tuple on line to create different wireframe models such as pyramid and flat hexagon increase the coordinates of cube_corners by so that the cube revolves around the center of the screenrather than rotating around its own center exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you delete or comment out lines to what happens if you change the tuples on line to <(( )( )( )( )( , )( )( ))>rotating cube |
6,985 | ya the royal game of ur is , -year-old game from mesopotamia archeologists rediscovered the game in the royal cemetery at urin modern-day southern iraqduring excavations between and the rules were reconstructed from the game board (shown in figure - and babylonian clay tabletand they're similar to parcheesi you'll need both luck and skill to win |
6,986 | two players each begin with seven tokens in their homeand the first player to move all seven to the goal is the winner players take turns throwing four dice these dice are four-pointed pyramid shapes called tetrahedrons each die has two marked pointsgiving an even chance that the dice come up marked or unmarked instead of diceour game uses coins whose heads act as the marked point the player can move token one space for each marked point that comes up this means they can move single token between zero and four spacesthough they're most likely to roll two spaces the tokens travel along the path indicated in figure - only one token may exist on space at time if token lands on an opponent' token while in the shared middle paththe opponent' token is sent back home if token lands on the middle flower squareit is safe from being landed on if token lands on any of the other four flower tilesthe player gets to roll again our game will represent the tokens with the letters and home home goal goal figure - the path each player' token takes from their home to their goal video featuring youtuber tom scott and british museum curator irving finkel discussing the royal game of ur can be found at www youtube com/watch? =wzskjlq royal game of ur |
6,987 | when you run royalgameofur pythe output will look like thisthe royal game of urby al sweigart --snip-xxxxxxx home goal ++++-- --+--^--+|*****|*****|*|*|****hgfe|****ts+-- --+++++++--^--|*****>*ijk|****lmnop+--^--+++++++-- --|*****|*****|*|*|****dcba|****rq++++--^--+-- --+ home goal ooooooo it is ' turn press enter to flip flipsh- - - select token to move spaceshome quit home landed on flower space and gets to go again press enter to continue --snip-how it works like in project "mancala,the spaces on the ascii-art game board are labeled with the letters through after rollingthe player can select space that contains their token to move that tokenor they can select home to begin moving token from their home to the board the program represents the board as dictionary with the keys 'ato 'tand the values of 'xand 'ofor the tokens (or for blank spaceadditionallythis dictionary has keys 'x_home''o_home''x_goal'and 'o_ goal'and the values for these keys are seven-character strings that represent how full the homes and goals are the 'xor 'ocharacters in these strings represent tokens at the home or goaland represents an empty slot the displayboard(function displays these seven-character strings on the screen """the royal game of urby al sweigart al@inventwithpython com , year old board game from mesopotamia two players knock each other back as they race for the goal more info view this code at project # |
6,988 | "" import randomsys x_player ' o_player ' empty set up constants for the space labels x_home 'x_home o_home 'o_home x_goal 'x_goal o_goal 'o_goal the spaces in left to righttop to bottom order all_spaces 'hgfetsijklmnopdcbarq x_track 'hefghijklmnopstg( stands for homeg stands for goal o_track 'habcdijklmnopqrg flower_spaces (' '' '' '' '' ' board_template "" {{ home goal ++++-- --+--^--+ |*****|***** |{*{{{|{*{ |****hgfe|****ts +-- --+++++++--^-- |***** {{{>{*{{{{ ijk|****lmnop +--^--+++++++-- -- |*****|***** |{*{{{|{*{ |****dcba|****rq ++++--^--+-- --+ home goal {{ "" def main() print('''the royal game of urby al sweigart this is , year old game two players must move their tokens from their home to their goal on your turn you flip four coins and can move one token number of spaces equal to the heads you got ur is racing gamethe first player to move all seven of their tokens to their goal wins to do thistokens must travel from their home to their goalroyal game of ur |
6,989 | home goal +---+---+---+- -+-^-+--- | <<<<<<<<<<<<^<|< | + --+---+---+---+---+---+---+-^- |>> |>> +^--+---+---+---+---+---+---+- - | |^<<<<<<<<<<<< <<< +---+---+---+-^-+- -+--- home goal if you land on an opponent' token in the middle trackit gets sent back home the **flower*spaces let you take another turn tokens in the middle flower space are safe and cannot be landed on ''' input('press enter to begin ' gameboard getnewboard( turn o_player while truemain game loop set up some variables for this turn if turn =x_player opponent o_player home x_home track x_track goal x_goal opponenthome o_home elif turn =o_player opponent x_player home o_home track o_track goal o_goal opponenthome x_home displayboard(gameboard input('it is turn '\' turn press enter to flip ' fliptally print('flips'end='' for in range( )flip coins result random randint( if result = print(' 'end=''tails else print(' 'end=''heads if ! print('-'end=''print separator fliptally +result print('end='' project # |
6,990 | if fliptally = input('you lose turn press enter to continue 'turn opponent swap turns to the other player continue ask the player for their movevalidmoves getvalidmoves(gameboardturnfliptallyif validmoves =[]print('there are no possible movesso you lose turn 'input('press enter to continue 'turn opponent swap turns to the other player continue while trueprint('select move'fliptally'spaces'end=''print(join(validmovesquit'move input(''lower(if move ='quit'print('thanks for playing!'sys exit(if move in validmovesbreak exit the loop when valid move is selected print('that is not valid move 'perform the selected move on the boardif move ='home'subtract tokens at home if moving from homegameboard[home- nexttrackspaceindex fliptally elsegameboard[moveempty set the "fromspace to empty nexttrackspaceindex track index(movefliptally movingontogoal nexttrackspaceindex =len(track if movingontogoalgameboard[goal+ check if the player has wonif gameboard[goal= displayboard(gameboardprint(turn'has won the game!'print('thanks for playing!'sys exit(elsenextboardspace track[nexttrackspaceindexcheck if the opponent has tile thereif gameboard[nextboardspace=opponentgameboard[opponenthome+ set the "tospace to the player' tokengameboard[nextboardspaceturn check if the player landed on flower space and can go againroyal game of ur |
6,991 | if nextboardspace in flower_spaces print(turn'landed on flower space and goes again ' input('press enter to continue ' else turn opponent swap turns to the other player def getnewboard() "" returns dictionary that represents the state of the board the keys are strings of the space labelsthe values are x_player o_playeror empty there are also counters for how many tokens are at the home and goal of both players "" board {x_home x_goal o_home o_goal set each space as empty to start for spacelabel in all_spaces board[spacelabelempty return board def displayboard(board) """display the board on the screen "" "clearthe screen by printing many newlinesso the old board isn' visible anymore print('\ xhometokens ('xboard[x_home]ljust( ' xgoaltokens ('xboard[x_goal]ljust( ' ohometokens ('oboard[o_home]ljust( ' ogoaltokens ('oboard[o_goal]ljust( ' add the strings that should populate board_template in order going from left to righttop to bottom spaces [ spaces append(xhometokens spaces append(xgoaltokens for spacelabel in all_spaces spaces append(board[spacelabel] spaces append(ohometokens spaces append(ogoaltokens print(board_template format(*spaces) def getvalidmoves(boardplayerfliptally) validmoves [contains the spaces with tokens that can move if player =x_player opponent o_player track x_track home x_home elif player =o_player opponent x_player track o_track home o_home project # |
6,992 | check if the player can move token from home if board[home and board[track[fliptally]=empty validmoves append('home' check which spaces have token the player can move for trackspaceindexspace in enumerate(track) if space ='hor space ='gor board[space!player continue nexttrackspaceindex trackspaceindex fliptally if nexttrackspaceindex >len(track) you must flip an exact number of moves onto the goal otherwise you can' move on the goal continue else nextboardspacekey track[nexttrackspaceindex if nextboardspacekey =' ' this token can move off the board validmoves append(space continue if board[nextboardspacekeyin (emptyopponent) if the next space is the protected middle spaceyou can only move there if it is empty if nextboardspacekey ='land board[' '=opponent continue skip this movethe space is protected validmoves append(space return validmoves if __name__ ='__main__' main(exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change nexttrackspaceindex =len(track on line to nexttrackspaceindex = what happens if you change result random randint( on line to result what error do you cause if you change board {x_home x_goal o_home o_goal on line to board {}royal game of ur |
6,993 | ay module seven-segment display is type of lcd component used to display numbers in pocket calculatorsmicrowave ovensand other small electronic devices through different combinations of seven line-shaped segments in an lcda seven-segment display can represent the digits through they look like this__ |____ __|__ __ ____|____ |__ ____ |__ |____ __ |__|____ |____the benefit of this program is that other programs can import it as module project "countdown,and project "digital clock,import the sevseg py file so they can use its getsevsegstr(function you can find more information about seven-segment displays and other variations at |
6,994 | even though it' modulesevseg py outputs sample demo of the digits it produces when you run the program directly the output will look like thisthis module is meant to be imported rather than run for examplethis codeimport sevseg mynumber sevseg getsevsegstr( print(mynumberwill print zero-padded to three digits__ __ |____|__|__ how it works the getsevsegstr(function first creates list of three strings the strings represent the topmiddleand bottom row of the numeric digits lines to have long list of ifelif statements for each digit (and the decimal point and minus signthat concatenates the rows of each digit to these strings these three strings are joined together with newlines on line so that the function returns single multiline string suitable to pass to print( """sevsegby al sweigart al@inventwithpython com seven-segment number display moduleused by the countdown and digital clock programs more info at view this code at tagsshortmodule"" """ labeled seven-segment displaywith each segment labeled to __a__ each digit in seven-segment display __ __ __ __ __ __ __ __ |__g______|__|__ |__ |__|__ |__|__ ____|__|____ |__d__|"" def getsevsegstr(numberminwidth= ) """return seven-segment display string of number the returned string will be padded with zeros if it is smaller than minwidth "" convert number to string in case it' an int or float number str(numberzfill(minwidth rows ['''''' for inumeral in enumerate(number) if numeral ='render the decimal point rows[ +seven-segment display module |
6,995 | project # rows[ +rows[ +continue skip the space in between digits elif numeral ='-'render the negative signrows[ +rows[ +__ rows[ +elif numeral =' 'render the rows[ +__ rows[ +'|rows[ +'|__|elif numeral =' 'render the rows[ +rows[ +|rows[ +|elif numeral =' 'render the rows[ +__ rows[ +__|rows[ +'|__ elif numeral =' 'render the rows[ +__ rows[ +__|rows[ +__|elif numeral =' 'render the rows[ +rows[ +'|__|rows[ +|elif numeral =' 'render the rows[ +__ rows[ +'|__ rows[ +__|elif numeral =' 'render the rows[ +__ rows[ +'|__ rows[ +'|__|elif numeral =' 'render the rows[ +__ rows[ +|rows[ +|elif numeral =' 'render the rows[ +__ rows[ +'|__|rows[ +'|__|elif numeral =' 'render the rows[ +__ rows[ +'|__|rows[ +__|add space (for the space in between numeralsif this isn' the last numeralif !len(number rows[ +rows[ +rows[ + |
6,996 | return '\njoin(rows if this program isn' being importeddisplay the numbers to if __name__ ='__main__' print('this module is meant to be imported rather than run ' print('for examplethis code:' print(import sevseg' print(mynumber sevseg getsevsegstr( )' print(print(mynumber)' print( print(will print zero-padded to three digits:' print(__ __ ' print('|____|' print('|__|__ 'after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingcreate new fonts for numberssuch as using five rows and the block character string returned by chr( look at the wikipedia article for seven-segment displays to find out how to display letters and then add those to sevseg py learn about sixteen-segment displays from sixteen-segment_display and create sixteenseg py module to generate numbers in that style exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change the single-space strings on lines and to empty strings what happens if you change the minwidth= default argument on line to minwidth= seven-segment display module |
6,997 | shining carpet the shininga psychological horror film directed by stanley kubricktakes place at the haunted overlook hotel the hotel carpet' hexagonal design became an iconic part of this famous movie the carpet features alternating and interlocking hexagons whose mesmerizing effect is well-suited for such an unnerving film the short program in this projectsimilar to project "hex grid,prints this repetitive pattern on the screen note that this program uses raw stringswhich prefix the opening quote with lowercase rso that the backslashes in the string aren' interpreted as escape characters |
6,998 | when you run shiningcarpet pythe output will look like this_ \____ \____ \____ \____ \____ \___ \____ \____ \____ \____ \____ \____ \\\\\\___ \____ \____ \____ \____ \____ \ __ \____ \____ \____ \____ \____ \__ __\\\\\\___ \____ \____ \____ \____ \____ \___ \____ \____ \____ \____ \____ \____ \\\\\\___ \____ \____ \____ \____ \____ \ __ \____ \____ \____ \____ \____ \__ __\\\\\\___ \____ \____ \____ \____ \____ \___ \____ \____ \____ \____ \____ \____ \\\\\\___ \____ \____ \____ \____ \____ \ __ \____ \____ \____ \____ \____ \__ __\\\\\\___ how it works the creation of program like this (or the similar project doesn' begin with coding but rather just drawing tessellating shapes in text editor once you've written out the patternyou can cut it down to the smallest unit to be tiled_ \___ \____ \___ \ __ \__ __\___ after you've copied and pasted this text into the source codeyou can write the rest of the program around it software is not just matter of sitting down and writing code from beginning to end every professional software developer goes through several iterations of tinkeringexperimentationand debugging the end result may be just nine lines of codebut small program doesn' necessarily imply that small amount of effort went into making it """shining carpetby al sweigart al@inventwithpython com displays tessellation of the carpet pattern from the shining view this code at tagstinybeginnerartistic"" set up the constantsshining carpet |
6,999 | y_repeat how many times to tessellate vertically for in range(y_repeat) print( ' \___x_repeat print( \____x_repeat print( '\x_repeat print( '___ \_x_repeat print( '__ \__x_repeat print( '__\___x_repeatexploring the program for practicetry creating patterns such as the following___|___|___|___|___|___|___|___|___|___|___|___|___|___|____|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ ___|___|___|___|___|___|___|___|___|___|___|___|___|___|____|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ ___|___|___|___|___|___|___|___|___|___|___|___|___|___|____|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ ()()()()()()()()()()()())))))))))))))))))))))))()()()()()()()()()()()())))))))))))))))))))))))()()()()()()()()()()()())))))))))))))))))))))))__ \____ \____ \____ \____ \__\____\____\____\____\____ \____ \____ \____ \____ \____ \____\____\____\____\______ \____ \____ \____ \____ \__\____\____\____\____\____ \____ \____ \____ \____ \____ \____\____\____\____\____\__ \__ \__ \__ \__ \__ \__ \__ \__ \__ __\__\__\__\__\__\__\__\__\______________________\__\__\__\__\__\__\__\__\__\____\__ \__ \__ \__ \__ \__ \__ \__ \__ \__ __\__\__\__\__\__\__\__\__\_____ ___ ___ ___ ___ ___ vvv vvv vvv vvv vvv vvv |(()|(()|(()|(()|(()|(()___ ___ ___ ___ ___ ___ vvv vvv vvv vvv vvv vvv )|(()|(()|(()|(()|(()|( project # |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.