id
int64
0
25.6k
text
stringlengths
0
4.59k
7,500
where variable is created determines what scope it is in when the dragon realm program first executes the line cave 'the variable cave is created inside the choosecave(function this means it is created in the choosecave(function' local scope it will be forgotten when choosecave(returnsand will be recreated if choosecave(is called second time the value of local variable isn' remembered between function calls parameters def checkcave(chosencave)the next function the program defines is named checkcave(notice the text chosencave between the parentheses this is parametera local variable that is assigned the argument passed when this function is called remember how for some function calls like str(or randint()you would pass one or more arguments between the parenthesesstr( ' random randint( you will also pass an argument when you call checkcave(this argument is stored in new variable named chosencave these variables are also called parameters for examplehere is short program that demonstrates defining function with parameterdef sayhello(name)print('helloname your name has str(len(name)letters 'sayhello('alice'sayhello('bob'spam 'carolsayhello(spampost questions to
7,501
if you run this programit would look like thishelloalice your name has letters hellobob your name has letters hellocarol your name has letters when you call sayhello()the argument is assigned to the name parameter parameters are just ordinary local variables like all local variablesthe values in parameters will be forgotten when the function call returns displaying the game results back to the game' source code print('you approach the cave 'time sleep( the time module has function called sleep(that pauses the program line passes the integer value so that time sleep(will pause the program for seconds print('it is dark and spooky 'time sleep( here the code prints some more text and waits for another seconds these short pauses add suspense to the gameinstead of displaying the text all at once in the previous jokes programyou called the input(function to pause until the player pressed the enter key herethe player doesn' have to do anything except wait couple seconds print(' large dragon jumps out in front of youhe opens his jaws and ' print( time sleep( what happens nextand how does the program decidethis is explained in the next section deciding which cave has the friendly dragon friendlycave random randint( line calls the random randint(function which will return either or this integer value is stored in friendlycave and is the cave with the friendly dragon
7,502
if chosencave =str(friendlycave)print('gives you his treasure!'line checks if the player' chosen cave in the chosencave variable (' or ' 'is equal to the friendly dragon cave but the value in friendlycave is an integer because random randint(returns integers you can' compare strings and integers with the =signbecause they will always be not equal to each other ' is not equal to and ' is not equal to so friendlycave is passed to str(functionwhich returns the string value of friendlycave this way the values will be the same data type and can be meaningfully compared to each other this code could also have been used to convert chosencave to an integer valueif int(chosencave=friendlycaveif the condition is trueline tells the player they have won the treasure elseprint('gobbles you down in one bite!'line is an else statement the else statement can only come after an if-block the else-block executes if the if statement' condition was false think of it as the program' way of saying"if this condition is true then execute the if-block or else execute the else-block remember to put the colon (the signafter the else keyword where the main part begins playagain 'yes while playagain ='yesor playagain =' 'line is the first line that isn' def statement or inside def-block this line is where the main part of the program begins the previous def statements merely defined the functions they didn' run the code inside of the functions line and are setting up loop that the rest of the game code is in at the end of the gamethe player can enter if they want to play again if they dothe execution enters the while loop to run the entire game all over again if they don'tthe while statement' condition will be false and the execution will move on to the end of the program and terminate post questions to
7,503
the first time the execution comes to this while statementline will have just assigned 'yesto the playagain variable that means the condition will be true this guarantees that the execution enters the loop at least once calling the functions in the program displayintro(line calls the displayintro(function this isn' python functionit is your function that you defined earlier on line when this function is calledthe program execution jumps to the first line in the displayintro(function on line when all the lines in the function are donethe execution jumps back to line and continues moving down cavenumber choosecave(line also calls function that you defined remember that the choosecave(function lets the player type in the cave they want to go into when the line ' return cave executesthe program execution jumps back to line and the choosecave(call evaluates to the return value this return value is stored in new variable named cavenumber then the program execution moves on to line checkcave(cavenumberline calls your checkcave(functionpassing the value in cavenumber as an argument not only does execution jump to line but the value in cavenumber is copied to the parameter chosencave inside the checkcave(function this is the function that will display either 'gives you his treasure!or 'gobbles you down in one bite!depending on the cave the player chose to go into asking the player to play again print('do you want to play again(yes or no)'playagain input(whether the player won or lostthey are asked if they want to play again the variable playagain stores what the player typed line is the last line of the while-blockso the program jumps back to line to check the while loop' conditionplayagain ='yesor playagain ='yif the player typed in the string 'yesor ' 'then the execution would enter the loop again at line
7,504
if the player typed in 'noor 'nor something silly like 'abraham lincoln'then the condition would be false the program execution would continue on to the line after the while-block but since there are no more lines after the while-blockthe program terminates one thing to notethe string 'yesis not equal to the string 'yesif the player typed in the string 'yes'then the while statement' condition would evaluate to false and the program would still terminate later programs in this book will show you how to avoid this problem you've just completed your second gamein dragon realmyou used lot of what you learned in the guess the number game and picked up few new tricks if you didn' understand some of the concepts in this programthen go over each line of the source code againand try changing the source code and see how the program changes in the next you won' create gamebut instead learn how to use feature of idle called the debugger designing the program dragon realm is simple game the other games in this book will be bit more complicated it sometimes helps to write down everything you want your game or program to do before you start writing code this is called "designing the program for exampleit may help to draw flow chart flow chart is picture that shows every possible action that can happen in the gameand which actions lead to which other actions figure - is flow chart for dragon realm to see what happens in the gameput your finger on the "startbox then follow one arrow from the box to another box your finger is like the program execution the program terminates when your finger lands on the "endbox when you get to the "check for friendly or hungry dragonboxyou can go to the "player winsbox or the "player losesbox this branching point shows how the program can do different things either wayboth paths will end up at the "ask to play againbox summary in the dragon realm gameyou created your own functions functions are mini-program within your program the code inside the function runs when the function is called by breaking up your code into functionsyou can organize your code into smaller and easier to understand sections arguments are values copied to the function' parameters when the function is called the function call itself evaluates to the return value post questions to
7,505
figure - flow chart for the dragon realm game you also learned about variable scopes variables created inside of function exist in the local scopeand variables created outside of all functions exist in the global scope code in the global scope cannot make use of local variables if local variable has the same name as variable in the global scopepython considers it separate variable and assigning new values to the local variable won' change the value in the global variable variable scopes might seem complicatedbut they are useful for organizing functions as separate pieces of code from the rest of the program because each function has its own local scopeyou can be sure that the code in one function won' cause bugs in other functions almost every program uses functions because they are so useful by understanding how functions workyou can save yourself lot of typing and make bugs easier to fix
7,506
using the debugger topics covered in this different types of errors idle' debugger stepping intooverand out go and quit break points bugs"on two occasions have been asked'praymr babbageif you put into the machine wrong figureswill the right answers come out? am not able rightly to apprehend the kind of confusion of ideas that could provoke such question -charles babbage th century originator the concept of programmable computer if you enter the wrong codethe computer won' give you the right program computer program will always do what you tell it tobut what you tell the program to do might not be the same as what you wanted the program to do these errors are bugs in computer program bugs happen when the programmer has not carefully thought about what exactly the program is doing there are three types of bugs that can happen with your programsyntax errors are type of bug that comes from typos when the python interpreter sees syntax errorit is because your code isn' written in proper python language python program with even single syntax error won' run runtime errors are bugs that happen while the program is running the program will work up until it reaches the line of code with the errorand then the program terminates with an error message (this is called crashingthe python interpreter will display "tracebackand show the line where the problem happens semantic errors are the trickiest to fix these bugs don' crash the programbut it isn' doing what the programmer intended for the program to do for exampleif the programmer wants the variable total to be the sum of the values in variables aband but writes total cthen the value in total will be wrong this could crash the program later onbut it is not immediately obvious where the semantic bug happened post questions to
7,507
finding bugs in program can be hardif you even notice them at allwhen running your programyou may discover that sometimes functions are not called when they are supposed to beor maybe they are called too many times you may code the condition for while loop wrongso that it loops the wrong number of times ( loop in your program that never exits is kind of bug called an infinite loop to stop this programyou can press ctrl- in the interactive shell to terminate the program any of these things could mistakenly happen in your code if you are not careful in factfrom the interactive shellgo ahead and create an infinite loop by typing this code in (you have to press enter twice to let the interactive shell know you are done typing in the whileblockwhile trueprint('press ctrl- to stop this infinite loop!!!'now press and hold down the ctrl key and press the key to stop the program the interactive shell will look like thispress ctrl- to stop this infinite loop!!press ctrl- to stop this infinite loop!!press ctrl- to stop this infinite loop!!press ctrl- to stop this infinite loop!!press ctrl- to stop this infinite loop!!traceback (most recent call last)file ""line in while trueprint('press ctrl- to stop this infinite loop!!!'keyboardinterrupt the debugger it can be hard to figure out how your code could be causing bug the lines of code get executed quickly and the values in variables change so often debugger is program that lets you step through your code one line at time in the same order that python executes them the debugger also shows you what values are stored in variables at each step starting the debugger in idleopen the dragon realm game you made in the last after opening the dragon py fileclick on the debug debugger to make the debug control window appear (figure -
7,508
figure - the debug control window figure - running the dragon realm game under the debugger post questions to
7,509
now when you run the dragon realm game by pressing idle' debugger will activate this is called running program "under debuggerin the debug control windowcheck the source and globals checkboxes when you run python programs under the debuggerthe program will stop before it executes the first instruction if you click on the file editor window' title bar (and you've checked the source checkbox in the debug control window)the first instruction is highlighted in gray the debug control window shows the execution is on line which is the import random line stepping the debugger lets you execute one instruction at time this is called stepping to execute single instructionclick the step button in the debug window go ahead and do this now python will execute the import random instructionand then stop before it executes the next instruction the debug control window will show the execution is now on line the import time line click the quit button to terminate the program for now here is summary of what happens when you click the step button when you run the dragon realm game under debugger press to start running dragon realm againthen follow these instructions click the step button twice to run the two import lines click the step button three more times to execute the three def statements click the step button again to define the playagain variable click go to run the rest of the programor click quit to terminate the program the debug control window will show you what line is about to be executed when you click the step button in the debug control window the debugger skipped line because it' blank line notice you can only step forward with the debuggeryou cannot go backwards globals area the globals area in the debug control window is where all the global variables can be seen rememberglobal variables are the variables that are created outside of any functions (that isin the global scopeas the three def statements execute and define functionsthey will appear in the globals area of the debug control window the text next to the function names in the globals area will look like "<function checkcave at >the module names also have confusing looking text next to themsuch as "you don' need to know what it
7,510
means to debug your programs just seeing that the functions and modules are there in the global area will tell you if the function has been defined or the module has been imported you can also ignore the __builtins____doc__and __name__ lines in the global area (those are variables that appear in every python program when the playagain variable is created it will show up in the global area next to the variable name will be the string 'yesthe debugger lets you see the values of all the variables in the program as the program runs this is useful for fixing bugs locals area there is also locals areawhich shows you the local scope variables and their values the local area will only have variables in it when the program execution is inside of function when the execution is in the global scopethis area is blank the go and quit buttons if you get tired of clicking the step button repeatedly and just want the program to run normallyclick the go button at the top of the debug control window this will tell the program to run normally instead of stepping to terminate the program entirelyjust click the quit button at the top of the debug control window the program will exit immediately this is helpful if you must start debugging again from the beginning of the program stepping intooverand out start the dragon realm program with the debugger keep stepping until the debugger is at line as shown in figure - this is the line with displayintro(when you click step againthe debugger will jump into this function call and appear on line the first line in the displayintro(function the kind of stepping you have been doing is called stepping into this is different from stepping overexplained next post questions to
7,511
figure - keep stepping until you reach line when the execution is paused at line clicking step one more time will step into the print(function the print(function is one of python' built-in functionsso it isn' useful to step through with the debugger python' own functions such as print()input()str()or random randint(have been carefully checked for errors you can assume they're not the parts causing bugs in your program so you don' want to waste time stepping through the internals of the print(function so instead of clicking step to step into the print(function' codeclick over this will step over the code inside the print(function the code inside print(will be executed at normal speedand then the debugger will pause once the execution returns from print(stepping over is convenient way to skip stepping through code inside function the debugger will now be paused at line cavenumber choosecave(click step one more time to step into the choosecave(function keep stepping through the code until line the input(call the program will wait until you type response into the interactive shelljust like when you run the program normally if you try clicking the step button nownothing will happen because the program is waiting for keyboard response
7,512
click back on the interactive shell window and type which cave you want to enter the blinking cursor must be on the bottom line in the interactive shell before you can type otherwise the text you type will not appear once you press enterthe debugger will continue to step lines of code again click the out button on the debug control window this is called stepping outbecause it will cause the debugger to step over as many lines as it needs to until execution has returned from the function it is in after it jumps outthe execution will be on the line after the line that called the function for exampleclicking out inside the displayintro(function on line would step until the function returned to the line after the call to displayintro(stepping out can save you from having to click step repeatedly to jump out of the function if you are not inside functionclicking out will cause the debugger will execute all the remaining lines in the program this is the same behavior as clicking the go button here' recap of what each button doesgo executes the rest of the code as normalor until it reaches break point (break points are described later step step one instruction if the line is function callthe debugger will step into the function over step one instruction if the line is function callthe debugger won' step into the functionbut instead step over the call out keeps stepping over lines of code until the debugger leaves the function it was in when out was clicked this steps out of the function quit immediately terminates the program find the bug the debugger can help you find the cause of bugs in your program as an examplehere is small program with bug the program comes up with random addition problem for the user to solve in the interactive shell windowclick on filethen new window to open new file editor window type this program into that windowand save the program as buggy py buggy py import random number random randint( number random randint( print('what is str(number str(number '?' answer input( if answer =number number post questions to
7,513
print('correct!' else print('nopethe answer is str(number number )type the program as it is aboveeven if you can already tell what the bug is then trying running the program by pressing this is simple arithmetic quiz that comes up with two random numbers and asks you to add them here' what it might look like when you run the programwhat is nopethe answer is that' bugthe program doesn' crash but it is not working correctly the program says the user is wrong even if they type the correct answer running the program under debugger will help find the bug' cause at the top of the interactive shell windowclick on debug debugger to display the debug control window in the debug control windowcheck all four checkboxes (stacksourcelocalsand globalsthis makes the debug control window provide the most information then press in the file editor window to run the program this time it will be run under the debugger import random the debugger starts at the import random line nothing special happens hereso just click step to execute it you will see the random module added to the globals area number random randint( click step again to run line new file editor window will appear with the random py file you have stepped inside the randint(function inside the random module python' built-in functions won' be the source of your bugsso click out to step out of the randint(function and back to your program then close the random py file' window number random randint( next timeyou can click over to step over the randint(function instead of stepping into it line is also randint(function call skip stepping into this code by clicking over print('what is str(number str(number '?'
7,514
line is print(call to show the player the random numbers you know what numbers the program will print even before it prints themjust look at the globals area of the debug control window you can see the number and number variablesand next to them are the integer values stored in those variables the number variable has the value and the number variable has the value when you click stepthe program will display the string in the print(call with these values the str(function will concatenate the string version of these integers when ran the debuggerit looked like figure - (your random numbers will probably be different figure - number is set to and number is set to answer input(clicking on step from line will execute input(the debugger waits until the player enters response into the program enter the correct answer (in my case into the interactive shell window the debugger will resume and move down to line if answer =number number print('correct!'line is an if statement the condition is that the value in answer must match the sum of number and number if the condition is truethen the debugger will move to line if the post questions to
7,515
condition is falsethe debugger will move to line click step one more time to find out where it goes else print('nopethe answer is str(number number )the debugger is now on line what happenedthe condition in the if statement must have been false take look at the values for number number and answer notice that number and number are integersso their sum would have also been an integer but answer is string that means that answer =number number would have evaluated to ' = string value and an integer value will always not equal each otherso the condition evaluated to false that is the bug in the program the bug is that the code has answer when it should have int(answerchange line to int(answer=number number and run the program again what is correctthis timethe program worked correctly run it one more time and enter wrong answer on purpose this will completely test the program you've now debugged this programrememberthe computer will run your programs exactly as you type themeven if what you type isn' what you intend break points stepping through the code one line at time might still be too slow often you'll want the program to run at normal speed until it reaches certain line break point is set on line when you want the debugger to take control once execution reaches that line if you think there' problem with your code onsayline just set break point on line (or maybe few lines before thatwhen execution reaches that linethe debugger will "break into the debuggerthen you can step through lines one at time to see what is happening clicking go will execute the program normally until it reaches another break point or the end of the program to set break pointright-click on the line in the file editor and select set breakpoint from the menu that appears the file editor will highlight that line with yellow you can set break points on as many lines as you want to remove the break pointclick on the line and select clear breakpoint from the menu that appears
7,516
figure - the file editor with two break points set example using break points here is program that simulates coin flips by calling random randint( the function returning the integer will be "headsand returning the integer will be "tailsthe flips variable will track how many coin flips have been done the heads variable will track how many came up heads the program will do "coin flipsone thousand times this would take person over an hour to dobut the computer can do it in one secondtype in the following code into the file editor and save it as coinflips py if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at coinflips py import random print(' will flip coin times guess how many times it will come up heads (press enter to begin)' input( flips heads while flips if random randint( = heads heads flips flips if flips = print(' flips and there have been str(headsheads ' if flips = print('at tossesheads has come up str(headstimes so far ' if flips = post questions to
7,517
print('half way doneand heads has come up str(headstimes ' print( print('out of coin tossesheads came up str(headstimes!' print('were you close?'the program runs pretty fast it spent more time waiting for the user to press enter than doing the coin flips let' say you wanted to see it do coin flips one by one on the interactive shell' windowclick on debug debugger to bring up the debug control window then press to run the program the program starts in the debugger on line press step three times in the debug control window to execute the first three lines (that islines and you'll notice the buttons become disabled because input(was called and the interactive shell window is waiting for the user to type something click on the interactive shell window and press enter (be sure to click beneath the text in the interactive shell windowotherwise idle might not receive your keystrokes you can click step few more timesbut you'll find that it would take quite while to get through the entire program insteadset break point on lines and the file editor will highlight these lines as shown in figure - figure - three break points set after setting the breakpointsclick go in the debug control window the program will run at normal speed until it reaches the next break point when flip is set to the condition for the if statement on line is true this causes line (where there' break point setto executewhich tells the debugger to stop the program and take over look at the debug control window in the globals section to see what the value of flips and heads are click go again and the program will continue until it reaches the next break point on line againsee how the values in flips and heads have changed if you click go againthe execution will continue until the next break point is reachedwhich is on line
7,518
summary writing programs is only the first part of programming the next part is making sure the code you wrote actually works debuggers let you step through the code one line at time you can examine which lines execute in what orderand what values the variables contain when this is too slowyou can set break points to stop the debugger only at the lines you want using the debugger is great way to understand what program is doing while this book provides explanations of all the game code in itthe debugger can help you find out more on your own post questions to
7,519
flow charts topics covered in this how to play hangman ascii art designing program with flow charts in this you'll design hangman game this game is more complicated than our previous gamebut also more fun because the game is advancedyou should first carefully plan it out by creating flow chart (explained laterin the next you'll actually write out the code for hangman how to play hangman hangman is game for two people usually played with paper and pencil one player thinks of wordand then draws blank on the page for each letter in the word then the second player tries to guess letters that might be in the word if they guess correctlythe first player writes the letter in the proper blank if they guess incorrectlythe first player draws single body part of the hanging man if the second player can guess all the letters in the word before the hangman is completely drawnthey win but if they can' figure it out in timethey lose sample run of hangman here is an example of what the player might see when they run the hangman program you'll write in the next the text that the player enters in shown in bold +---========missed letters_
7,520
guess letter +---========missed letters_ guess letter +--- ========missed letterso guess letter +--- ========missed lettersor guess letter +--- ========missed lettersor guess letter you have already guessed that letter choose again post questions to
7,521
guess letter yesthe secret word is "cat"you have wondo you want to play again(yes or nono ascii art the graphics for hangman are keyboard characters printed on the screen this type of graphics is called ascii art (pronounced "ask-ee")which was sort of precursor to emojii here is cat drawn in ascii artxx xxx /xxx xx xxx xxx \__ __xxx xxx xx xxx \__ /xxxxxxxxx xx xx xx xx xxxxx /xx xxx xx /xx \____ \____z xxx \______\____ xxx___ x____o\_____xx |oo /xx\__ __xx \x_\____ \designing program with flowchart this game is bit more complicated than the ones you've seen so farso take moment to think about how it' put together first you'll create flow chart (like the one at the end of the dragon realm to help visualize what this program will do this will go over what flow charts are and why they are useful the next will go over the source code to the hangman game flow chart is diagram that shows series of steps as boxes connected with arrows each box represents stepand the arrows show the steps leads to which other steps put your finger on the
7,522
"startbox of the flow chart and trace through the program by following the arrows to other boxes until you get to the "endbox figure - is complete flow chart for hangman you can only move from one box to another in the direction of the arrow you can never go backwards unless there' second arrow going backlike in the "player already guessed this letterbox figure - the complete flow chart for what happens in the hangman game of courseyou don' have to make flow chart you could just start writing code but often once you start programming you'll think of things that must be added or changed you may end up post questions to
7,523
having to delete lot of your codewhich would be waste of effort to avoid thisit' always best to plan how the program will work before you start writing it creating the flow chart your flow charts don' always have to look like this one as long as you understand the flow chart you madeit will be helpful when you start coding flow chart that begins with just "startand an "endboxas shown in figure - figure - begin your flow chart with start and end box
7,524
now think about what happens when you play hangman firstthe computer thinks of secret word then the player will guess letters add boxes for these eventsas shown in figure - the new boxes in each flow chart have dashed outline around them the arrows show the order that the program should move that isfirst the program should come up with secret wordand after that it should ask the player to guess letter figure - draw out the first two steps of hangman as boxes with descriptions but the game doesn' end after the player guesses one letter it needs to check if that letter is in the secret word or not post questions to
7,525
branching from flowchart box there are two possibilitiesthe letter is either in the word or not you'll add two new boxes to the flowchartone for each case this creates branch in the flow chartas show in figure - figure - the branch has two arrows going to separate boxes
7,526
if the letter is in the secret wordcheck if the player has guessed all the letters and won the game if the letter isn' in the secret wordanother body part is added to the hanging man add boxes for those cases too you don' need an arrow from the "letter is in secret wordbox to the "player has run out of body parts and losesboxbecause it' impossible to lose as long as the player guesses correctly it' also impossible to win as long as the player is guessing incorrectlyso you don' need to draw that arrow either the flow chart now looks like figure - figure - after the branchthe steps continue on their separate paths post questions to
7,527
ending or restarting the game once the player has won or lostask them if they want to play again with new secret word if the player doesn' want to play againthe program will end if the program doesn' endit thinks up new secret word this is shown in figure - figure - the flow chart branches when asking the player to play again
7,528
guessing again the player doesn' guess letter just once they have to keep guessing letters until they win or lose you'll draw two new arrowsas shown in figure - figure - the new arrows (outlinedshow the player can guess again post questions to
7,529
what if the player guesses the same letter againrather than have them win or lose in this caseallow them to guess different letter instead this new box is shown in figure - figure - adding step in case the player guesses letter they already guessed offering feedback to the player the player needs to know how they're doing in the game the program should show them the hangman board and the secret word (with blanks for the letters they haven' guessed yetthese visuals will let them see how close they are to winning or losing the game
7,530
this information is updated every time the player guesses letter add "show the board and blanks to the player box to the flow chart between the "come up with secret wordand the "ask player to guess letterboxes these boxes are shown in figure - figure - adding "show the board and blanks to the player to give the player feedback that looks goodthis flow chart completely maps out everything that can happen in hangman and in what order when you design your own gamesa flow chart can help you remember everything you need to code post questions to
7,531
summary it may seem like lot of work to sketch out flow chart about the program first after allpeople want to play gamesnot look at flowchartsbut it is much easier to make changes and notice problems by thinking about how the program works before writing the code for it if you jump in to write the code firstyou may discover problems that require you to change the code you've already written every time you change your codeyou are taking chance you create new bugs by changing too little or too much it is much better to know what you want to build before you build it
7,532
hangman topics covered in this multi-line strings methods lists the append(and reverse(list methods the lower()upper()split()startswith()and endswith(string methods the in and not in operators the range(and list(functions del statements for loops elif statements this game introduces many new conceptsbut don' worry you'll experiment with these programming concepts in the interactive shell first you'll learn about methodswhich are functions attached to values you'll also learn about new type of loop called for loop and new data type called list once you understand these conceptsit will be much easier to program hangman source code of hangman this game is bit longer than the previous gamesbut much of it is the ascii art for the hangman pictures enter the following into the file editor and save it as hangman py hangman py import random hangmanpics ['' +--- =========''''' +---post questions to
7,533
=========''''' +--- =========''''' +--- / =========''''' +--- /| =========''''' +--- /| =========''''' +--- /| ========='''
7,534
words 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebrasplit( def getrandomword(wordlist) this function returns random string from the passed list of strings wordindex random randint( len(wordlist return wordlist[wordindex def displayboard(hangmanpicsmissedletterscorrectletterssecretword) print(hangmanpics[len(missedletters)] print( print('missed letters:'end=' for letter in missedletters print(letterend=' print( blanks '_len(secretword for in range(len(secretword))replace blanks with correctly guessed letters if secretword[iin correctletters blanks blanks[:isecretword[iblanks[ + : for letter in blanksshow the secret word with spaces in between each letter print(letterend=' print( def getguess(alreadyguessed) returns the letter the player entered this function makes sure the player entered single letterand not something else while true print('guess letter ' guess input( guess guess lower( if len(guess! print('please enter single letter ' elif guess in alreadyguessed print('you have already guessed that letter choose again ' elif guess not in 'abcdefghijklmnopqrstuvwxyz' print('please enter letter 'post questions to
7,535
else return guess def playagain() this function returns true if the player wants to play againotherwise it returns false print('do you want to play again(yes or no)' return input(lower(startswith(' ' print(' ' missedletters ' correctletters ' secretword getrandomword(words gameisdone false while true displayboard(hangmanpicsmissedletterscorrectletterssecretword let the player type in letter guess getguess(missedletters correctletters if guess in secretword correctletters correctletters guess check if the player has won foundallletters true for in range(len(secretword)) if secretword[inot in correctletters foundallletters false break if foundallletters print('yesthe secret word is "secretword '"you have won!' gameisdone true else missedletters missedletters guess check if player has guessed too many times and lost if len(missedletters=len(hangmanpics displayboard(hangmanpicsmissedletterscorrectletterssecretword print('you have run out of guesses!\nafter str(len(missedletters)missed guesses and str(len(correctletters)correct guessesthe word was "secretword '"' gameisdone true
7,536
done ask the player if they want to play again (but only if the game is if gameisdoneif playagain()missedletters 'correctletters 'gameisdone false secretword getrandomword(wordselsebreak how the code works import random the hangman program randomly selected secret word from list of secret words the random module will provide this abilityso line imports it hangmanpics ['' +--- ========='''''the rest of the code is too big to show here this one assignment statement stretches over lines to in the source code to help you understand what this code meanslet' learn about multi-line strings multi-line strings so far all strings have been on one line and had one quote character at the start and end howeverif you use three quotes at the start and end then the string can go across several linesfizz '''dear alicei will return to carol' house at the end of the month will see you then your friendbob''print(fizzpost questions to
7,537
dear alicei will return to carol' house at the end of the month will see you then your friendbob these are multi-line strings in multi-line stringthe newline characters are included as part of the string you don' have to use the \ escape characteror escape quotes as long as you don' use three of them together this makes the code easier to read for large amounts of text constant variables the hangmanpics variable' name is in all capitals this is the programming convention for constant variables constants are variables meant to have values that never changes from their first assignment statement although you can change the value in hangmanpics just like any other variablethe all-caps name reminds you to not do so since the hangmanpics variable never needs to changeit' marked as constant like all conventionsyou don' have to follow it but following this convention makes it easier for other programmers to read your code they'll know that hangmanpics will always have the value it was assigned on line lists list value can contain several other values inside it try entering this into the interactive shellspam ['life''the universe''everything' spam ['life''the universe''everything' this list value in spam contains four values when typing the list value into your codeit begins with square bracket and ends with square bracket this is like how strings begin and end with quote character commas separate the individual values inside of list these values are also called items indexes try entering animals ['aardvark''anteater''antelope''albert'into the interactive shell to store list in the variable animals the square brackets are also used to access
7,538
an item inside list try entering animals[ ]animals[ ]animals[ ]and animals[ into the interactive shell to see how they evaluateanimals ['aardvark''anteater''antelope''albert'animals[ 'aardvarkanimals[ 'anteateranimals[ 'antelopeanimals[ 'albertthe number between the square brackets is the index in pythonthe index of the first item in list is the second item is at index the third item is at index and so on because the indexes begin at not we say that python lists are zero-indexed lists are good for storing several values without using variable for each one otherwisethe code would look like thisanimals 'aardvarkanimals 'anteateranimals 'antelopeanimals 'albertthis code would be hard to manage if you have hundreds or thousands of strings but list can easily contain any number of values using the square bracketsyou can treat items in the list just like any other value try entering animals[ animals[ into the interactive shellanimals[ animals[ 'aardvarkantelopethe evaluation looks like thisanimals[ animals[ 'aardvarkanimals[ 'aardvark'antelopev 'aardvarkantelopeindexerror post questions to
7,539
if you try accessing an index that is too largeyou'll get an indexerror that will crash your program try entering the following into the interactive shellanimals ['aardvark''anteater''antelope''albert'animals[ traceback (most recent call last)file ""line in animals[ indexerrorlist index out of range changing the values of list items with index assignment you can also use the square brackets to change the value of an item in list try entering the following into the interactive shellanimals ['aardvark''anteater''antelope''albert'animals[ 'anteateranimals ['aardvark''anteater''antelope''albert'the new 'anteaterstring overwrites the second item in the animals list so animals[ will evaluate to the list' second item in expressionsbut you can also use it on the left side of an assignment statement to assign value as the list' second item list concatenation you can join lists into one list with the operatorjust like you can join strings joining lists with the operator is list concatenation try entering the following into the interactive shell[ ['apples''oranges'['alice''bob'[ 'apples''oranges''alice''bob'['apples'['oranges'will evaluate to ['apples''oranges'but ['apples''orangeswill result in an error you cannot add list value and string value instead of two list values if you want to add non-list values to listuse the append(method (described laterthe in operator the in operator can tell you if value is in list or not expressions that use the in operator return boolean valuetrue if the value is in the list and false if it isn' try entering the following into the interactive shellanimals ['aardvark''anteater''antelope''albert''antelopein animals
7,540
true the expression 'antelopein animals returns true because the string 'antelopeis one of the values in the animals list it is located at index but if you type the expression 'antin animalsthis will return false because the string 'antdoesn' exist in the list animals ['aardvark''anteater''antelope''albert''antelopein animals true 'antin animals false the in operator also works for strings it checks if one string exists in another try entering the following into the interactive shell'helloin 'alice said hello to bob true deleting items from lists with del statements del statement will delete an item at certain index from list try entering the following into the interactive shellspam [ del spam[ spam [ notice that when you deleted the item at index the item that used to be at index became the new value at index the item that used to be at index moved to be the new value at index everything above the deleted item moved down one index you can type del spam[ again and again to keep deleting items from the listspam [ del spam[ spam [ del spam[ spam [ del spam[ spam post questions to
7,541
[ the del statement is statementnot function or an operator it doesn' have parentheses or evaluate to return value lists of lists lists can contain other valuesincluding other lists let' say you have list of groceriesa list of choresand list of your favorite pies you can put all three lists into another list try entering the following into the interactive shellgroceries ['eggs''milk''soup''apples''bread'chores ['clean''mow the lawn''go grocery shopping'favoritepies ['apple''frumbleberry'listoflists [grocerieschoresfavoritepieslistoflists [['eggs''milk''soup''apples''bread']['clean''mow the lawn''go grocery shopping']['apple''frumbleberry']to get an item inside the list of listsyou would use two sets of square brackets like thislistoflists[ ][ which would evaluate to the string 'go grocery shoppingthis is because listoflists[ ][ evaluates to ['clean''mow the lawn''go grocery shopping'][ that finally evaluates to 'go grocery shopping'listoflists[ ][ [['eggs''milk''soup''apples''bread']['clean''mow the lawn''go grocery shopping']['apple''frumbleberry']][ ][ ['clean''mow the lawn''go grocery shopping'][ 'go grocery shoppingfigure - is another example of list of listsalong with some of the indexes that point to the items the arrows point to indexes of the inner lists themselves the image is also flipped on its side to make it easier to read methods methods are functions attached to value for exampleall string values have lower(methodwhich returns copy of the string value in lowercase you can call it like 'hellolower()which returns 'helloyou cannot call lower(by itself and you do not
7,542
pass string argument to lower((as in lower('hello')you must attach the method call to specific string value using period the next section describes string methods further figure - the indexes of list of lists the lower(and upper(string methods try entering 'hello world!lower(into the interactive shell to see an example of this method'hello world!lower('hello world!there is also an upper(method for stringswhich returns string with all the characters in uppercase try entering 'hello world!upper(into the interactive shell'hello world!upper('hello worldpost questions to
7,543
because the upper(method returns stringyou can call method on that string also try entering 'hello world!upper(lower(into the interactive shell'hello world!upper(lower('hello world!'hello world!upper(evaluates to the string 'hello world!'and then string' lower(method is called this returns the string 'hello world!'which is the final value in the evaluation 'hello world!upper(lower( 'hello world!lower( 'hello world!the order is important 'hello world!lower(upper(isn' the same as 'hello world!upper(lower()'hello world!lower(upper('hello world!that evaluation looks like this'hello world!lower(upper( 'hello world!upper( 'hello world!if string is stored in variableyou can call string method on that variable look at this examplespam 'hello world!spam upper('hello world!this does not change the value in spam the spam variable will still contain 'hello world!note that the integer and float data types don' have any methods
7,544
the reverse(and append(list methods the list data type also has methods the reverse(method will reverse the order of the items in the list try entering spam [ 'meow''woof']and then spam reverse(to reverse the list then enter spam to view the contents of the variable spam [ 'meow''woof'spam reverse(spam ['woof''meow' the most common list method you'll use is append(this method will add the value you pass as an argument to the end of the list try entering the following into the interactive shelleggs [eggs append('hovercraft'eggs ['hovercraft'eggs append('eels'eggs ['hovercraft''eels'eggs append( eggs ['hovercraft''eels' these methods do change the lists they are called on they don' return new list we say that these methods change the list in-place the split(list method line is long line of codebut it is really just simple assignment statement this line also uses the split(methodwhich is method for the string data type like the lower(and upper(methods words 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebrasplit(post questions to
7,545
this assignment statement has just one long stringfull of words separated by spaces and at the end of the string is split(method call the split(method evaluates to list with each word in the string as single list item the "splitoccurs wherever space occurs in the string it is easier to type the code using split(if you created it as list to begin withyou would have to type['ant''baboon''badger'and so onwith quotes and commas for every word for exampletry entering the following into the interactive shellsentence input(my very energetic mother just served us nachos sentence split(['my''very''energetic''mother''just''served''us''nachos 'the result is list of nine stringsone string for each of the words in the original string the spaces are not included in any of the items in the list you can also add your own words to the string on line or remove any you don' want to be in the game just make sure that spaces separate the words how the code works line defines the getrandomword(function list argument will be passed for its wordlist parameter this function will return single secret word from the list in wordlist def getrandomword(wordlist) this function returns random string from the passed list of strings wordindex random randint( len(wordlist return wordlist[wordindexline stores random index for this list in the wordindex variable you do this by calling randint(with two arguments the first argument is (for the first possible indexand the second argument is the value that the expression len(wordlist evaluates to (for the last possible index in wordlistlist indexes start at not if you have list of three itemsthe index of the first item is the index of the second item is and the index of the third item is the length of this list is but the index would be after the last index this is why line subtracts from the length the code on line will work no matter what the size of wordlist is now you can add or remove strings to wordlist if you like
7,546
the wordindex variable will be set to random index for the list passed as the wordlist parameter line will return the element in wordlist at the integer index stored in wordindex let' pretend ['apple''orange'grape'was passed as the argument to getrandomword(and that randint( returned the integer that would mean that line would evaluate to return wordlist[ ]and then evaluate to return 'grapethis is how the getrandomword(returns random string in the wordlist list so the input to getrandomword(is list of stringsand the return value output is randomly selected string from that list this will be useful for the hangman game to select secret word for the player to guess displaying the board to the player nextyou need function to print the hangman board on the screen it will also display how many letters the player has correctly (and incorrectlyguessed def displayboard(hangmanpicsmissedletterscorrectletterssecretword) print(hangmanpics[len(missedletters)] print(this code defines new function named displayboard(this function has four parametershangmanpics list of multi-line strings that will display the board as ascii art (the global hangmanpics variable will be passed for this parameter missedletters string of the letters the player has guessed that are not in the secret word correctletters string of the letters the player has guessed that are in the secret word secretword string of the secret word that the player is trying to guess the first print(function call will display the board hangmanpics will be list of strings for each possible board hangmanpics[ shows an empty gallowshangmanpics[ shows the head (when the player misses one letter)hangmanpics[ shows head and body (when the player misses two letters)and so on until hangmanpics[ which shows the full hangman the number of letters in missedletters will reflect how many incorrect guesses the player has made call len(missedlettersto find out this number soif missedletters is 'aetrthen len('aetr'will return printing hangmanpics[ will display the appropriate hangman board for misses this is what hangmanpics[len(missedletters)on line evaluates to post questions to
7,547
print('missed letters:'end='for letter in missedlettersprint(letterend='print(line prints the string 'missed letters:with space character at the end instead of newline remember that the keyword argument end=uses only one sign (like =)not two (like ==line is new type of loopcalled for loop for loop often uses the range(function both are explained in the next two sections the range(and list(functions when called with one argumentrange(will return range object of integers from up to (but not includingthe argument this range object can be converted to the more familiar list data type with the list(function try entering list(range( )into the interactive shelllist(range( )[ list('hello'[' '' '' '' '' 'the list(function is similar to the str(or int(functions it takes the value it is passed and returns list it' easy to generate huge lists with the range(function try entering in list(range( )into the interactive shelllist(range( )[ skipped for brevity the list is so hugethat it won' even all fit onto the screen but you can store the list into variablespam list(range( )if you pass two integer arguments to range()the range object it returns is from the first integer argument up to (but not includingthe second integer argument try entering list(range( )into the interactive shelllist(range( )[
7,548
the range(function is often used in for loopswhich are much like the while loops you've already seen for loops the for loop is useful for looping over list of values this is different from the while loopwhich loops as long as certain condition is true for statement begins with the for keywordfollowed by new variable namefollowed by the in keywordfollowed by an iterable valueand ending with colon an iterable is value of the listrangeor string data types there are also other data types that are considered iterables which will be introduced later each time the program execution iterates through the loop the new variable in the for statement is assigned the value of the next item in the list for in range( )print(' is set to str( ) is set to is set to is set to is set to is set to the range object returned by range( is equivalent to the list [ in for statement the first time the execution goes through the code in the for-blockthe variable will be set to on the next iterationi will be set to and so on the for statement automatically converts the range object returned by range(into listso there' no need for list(range( )in the for statement just use range( lists and strings are also iterable data types you can use them in for statements try entering the following into the interactive shellfor thing in ['cats''pasta''programming''spam']print(' really like thingi really like cats really like pasta really like programming really like spam for in 'hello'print(ipost questions to
7,549
while loop equivalent of for loop the for loop is similar to the while loopbut when you only need to iterate over items in listusing for loop is much less code to type this is while loop that acts the same as the previous for loop by adding extra codeiterableval ['cats''pasta''programming''spam'index while (index len(iterableval))thing iterableval[indexprint(' really like thingindex index really like cats really like pasta really like programming really like spam but using the for statement automatically does this extra code and makes programming easier since you have less to type the rest of the displayboard(function displays the missed letters and creates the string of the secret word with all the not yet guessed letters as blanks print('missed letters:'end='for letter in missedlettersprint(letterend='print(the for loop on line will iterate over each character in the missedletters string and print them on the screen remember that the end=will replace the newline character that is printed after the string with single space character for exampleif missedletters was 'ajtwthis for loop would display
7,550
slicing list slicing creates new list value with subset of another list' items in codespecify two indexes (the beginning and endwith colon in the square brackets after list for exampletry entering the following into the interactive shellspam ['apples''bananas''carrots''dates'spam[ : ['bananas''carrots'the expression spam[ : evaluates to list with items from index up to (but not includingindex in spam if you leave out the first indexpython will automatically think you want index for the first indexspam ['apples''bananas''carrots''dates'spam[: ['apples''bananas'if you leave out the second indexpython will automatically think you want the rest of the listspam ['apples''bananas''carrots''dates'spam[ :['carrots''dates'slicing is simple way to get subset of the items in list you use slices with strings in the same way you use them with lists each character in the string is like an item in the list try entering the following into the interactive shellmyname 'zophie the fat catmyname[ : 'ie the fmyname[: 'zophie themyname[ :'the fat catthe next part of the code in hangman uses slicing displaying the secret word with blanks now you want code to print the secret wordbut with blank lines for the letters that have not been guessed you can use the character (called the underscore characterfor this first create post questions to
7,551
string with nothing but one underscore for each letter in the secret word then replace the blanks for each letter in correctletters so if the secret word was 'otterthen the blanked out string would be '(five charactersif correctletters was the string 'rtyou would change the string to '_tt_rline to is the code that does that blanks '_len(secretwordline creates the blanks variable full of underscores using string replication remember that the operator can also be used on string and an integerso the expression ' evaluates to 'this will make sure that blanks has the same number of underscores as secretword has letters for in range(len(secretword))replace blanks with correctly guessed letters if secretword[iin correctletters blanks blanks[:isecretword[iblanks[ + :line has for loop to go through each letter in secretword and replace the underscore with the actual letter if it exists in correctletters for examplepretend the value of secretword is 'otterand the value in correctletters is 'tryou would want the string '_tt_rdisplayed to the player let' figure out how to create this string line ' len(secretwordcall would return the range(len(secretword)call becomes range( )which makes the for loop iterate over and because the value of will take on each value in [ ]the code in the for loop is the same as thisif secretword[ in correctlettersblanks blanks[: secretword[ blanks[ :if secretword[ in correctlettersblanks blanks[: secretword[ blanks[ :if secretword[ in correctlettersblanks blanks[: secretword[ blanks[ :if secretword[ in correctlettersblanks blanks[: secretword[ blanks[ :
7,552
if secretword[ in correctlettersblanks blanks[: secretword[ blanks[ :if you are confused as to what the value of something like secretword[ or blanks[ :isthen look at figure - it shows the value of the secretword and blanks variablesand the index for each letter in the string figure - the indexes of the blanks and secretword strings if you replace the list slices and the list indexes with the values that they representthe loop code would be the same as thisif 'oin 'tr'false blanks '' '____this line is skipped if 'tin 'tr'true blanks ' ' '___this line is executed if 'tin 'tr'true blanks '_t' '__this line is executed if 'ein 'tr'false blanks '_tt' '_this line is skipped if 'rin 'tr'true blanks '_tt_' 'this line is executed blanks now has the value '_tt_rthe above code examples all do the same thing when secretword is 'otterand correctletters is 'trthe next few lines of code print the new value of blanks with spaces between each letter post questions to
7,553
for letter in blanksshow the secret word with spaces in between each letter print(letterend=' print(get the player' guess the getguess(function will be called so that the player can enter letter to guess the function returns the letter the player guessed as string furthergetguess(will make sure that the player types valid letter before returning from the function def getguess(alreadyguessed) returns the letter the player entered this function makes sure the player entered single letterand not something else string of the letters the player has guessed is passed as the argument for the alreadyguessed parameter then the getguess(function asks the player to guess single letter this single letter will be getguess()' return value while trueprint('guess letter 'guess input(guess guess lower(line ' while loop will keep asking the player for letter until they enter text that is single letter letter they have not guessed previously the condition for the while loop is simply the boolean value true that means the only way execution will ever leave this loop is by executing break statement (which leaves the loopor return statement (which leaves not just the loop but the entire functionthe code inside the loop asks the player to enter letterwhich is stored in the variable guess if the player entered capitalized letterit will be overwritten with to lowercase letter on line elif ("else if"statements the next part of the hangman program uses elif statements you can think of elif "else ifstatements as saying "if this is truedo this or else if this next condition is truedo that or else if none of them are truedo this last thing
7,554
take look at the following codeif catname ='fuzzball'print('your cat is fuzzy 'elif catname ='spots'print('your cat is spotted 'elseprint('your cat is not fuzzy or spotted 'if the catname variable is equal to the string 'fuzzball'then the if statement' condition is true and the if-block tells the user that their cat is fuzzy howeverif this condition is falsethen python tries the elif ("else if"statement' condition next if catname is 'spots'then the 'your cat is spotted string is printed to the screen if both are falsethen the code tells the user their cat isn' fuzzy or spotted you can have as many elif statements as you wantif catname ='fuzzball'print('your cat is fuzzy 'elif catname ='spots'print('your cat is spotted 'elif catname ='chubs'print('your cat is chubby 'elif catname ='puff'print('your cat is puffy 'elseprint('your cat is neither fuzzy nor spotted nor chubby nor puffy 'when one of the elif conditions is trueits code is executed and then execution jumps to the first line past the else-block so one and only one of the blocks in the if-elif-else statements will be executed you can also leave off the else-block if you don' need oneand just have ifelif statements making sure the player entered valid guess if len(guess! print('please enter single letter 'elif guess in alreadyguessedprint('you have already guessed that letter choose again 'elif guess not in 'abcdefghijklmnopqrstuvwxyz'print('please enter letter 'elsereturn guess post questions to
7,555
the guess variable contains player' letter guess the program needs to make sure they typed in valid guessone and only one lowercase letter if they didn'tthe execution should loop back and ask them for letter again line ' condition checks if guess is not one character long line ' condition checks if guess already exists inside the alreadyguessed variable line ' condition checks if guess is not lowercase letter if all of these conditions are falsethen the else statement' block executes and getguess(returns the value in guess on line rememberonly one of the blocks in if-elif-else statements will be executed asking the player to play again def playagain() this function returns true if the player wants to play againotherwise it returns false print('do you want to play again(yes or no)' return input(lower(startswith(' 'the playagain(function has just print(function call and return statement the return statement has an expression that looks complicatedbut you can break it down here' step by step look at how python evaluates this expression if the user types in yes input(lower(startswith(' ' 'yeslower(startswith(' ' 'yesstartswith(' ' true the point of the playagain(function is to let the player type in yes or no to tell the program if they want to play another round of hangman the player should be able to type yesyesyor anything else that begins with "yin order to mean "yesif the player types in yesthen the return value of input(is the string 'yesand 'yeslower(returns the lowercase version of the attached string so the return value of 'yeslower(is 'yesbut there' the second method callstartswith(' 'this function returns true if the associated string begins with the string parameter between the parenthesesand false if it doesn' the return value of 'yesstartswith(' 'is true
7,556
now you have evaluated this expressionwhat it does is let the player type in responselowercases the responsechecks if it begins with the letter ' 'then returns true if it does and false if it doesn' on side notethere' also an endswith(somestringstring method that will return true if the string ends with the string in somestring and false if it doesn' endswith(is sort of like the opposite of startswith(review of the hangman functions that' all the functions we are creating for this gamelet' review themgetrandomword(wordlistwill take list of strings passed to itand return one string from it that is how word is chosen for the player to guess displayboard(hangmanpicsmissedletterscorrectletterssecretwordwill show the current state of the boardincluding how much of the secret word the player has guessed so far and the wrong letters the player has guessed this function needs four parameters passed to work correctly hangmanpics is list of strings that hold the ascii art for each possible hangman board correctletters and missedletters are strings made up of the letters that the player has guessed that are in and not in the secret wordrespectively and secretword is the secret word the player is trying to guess this function has no return value getguess(alreadyguessedtakes string of letters the player has already guessed and will keep asking the player for letter that isn' in alreadyguessed this function returns the string of the valid letter the player guessed playagain(is function that asks if the player wants to play another round of hangman this function returns true if the player does and false if the player doesn' after the functions is the code for the main part of the program at line everything previous was just function definitions and large assignment statement for hangmanpics setting up the variables print(' ' missedletters ' correctletters ' secretword getrandomword(words gameisdone false post questions to
7,557
line is the first print(call that executes when the game is run it displays the title of the game next is assigning blank strings for missedletters and correctletters since the player hasn' guessed any missed or correct letters yet the getrandomword(wordscall will evaluate to randomly selects word from the words list line sets gameisdone to false the code will set gameisdone to true when it wants to signal that the game is over and should ask the player if they want to play again displaying the board to the player while true displayboard(hangmanpicsmissedletterscorrectletterssecretwordthe while loop' condition is always truewhich means it will loop forever until break statement is encountered (this happens later on line line calls the displayboard(functionpassing it the list of hangman ascii art pictures and the three variables set on lines and based on how many letters the player has correctly guessed and missedthis function displays the appropriate hangman board to the player letting the player enter their guess let the player type in letter guess getguess(missedletters correctlettersthe getguess(function needs all the letters in missedletters and correctletters combinedso line concatenates the strings in these variables and passes the result as the argument this argument is needed by getguess(because the function has to check if the player types in letter that they have already guessed checking if the letter is in the secret word if guess in secretwordcorrectletters correctletters guess if the guess string exists in secretwordthen concatenate guess to the end of the correctletters string this string will be the new value of correctletters
7,558
checking if the player has won check if the player has won foundallletters true for in range(len(secretword))if secretword[inot in correctlettersfoundallletters false break how can the program know if the player has guessed every letter in the secret wordwellcorrectletters has each letter that the player correctly guessed and secretword is the secret word itself but you can' just check if correctletters =secretword because consider this caseif secretword was the string 'otterand correctletters was the string 'orte'then correctletters =secretword would be false even though the player has guessed each letter in the secret word the only way you can be sure the player won is to iterate over each letter in secretword and see if it exists in correctletters ifand only ifevery letter in secretword exists in correctletters will the player have won if you find letter in secretword that doesn' exist in correctlettersyou know that the player has not guessed all the letters the new variable foundallletters is set to true on line before the loop begins the loop starts out assuming that all the letters in the secret word have been found but the loop' code on line will change foundallletters to false the first time it finds letter in secretword that isn' in correctletters won!' if foundalllettersprint('yesthe secret word is "secretword '"you have gameisdone true if all letters in the secret word have been foundthe player is told they have won and gameisdone is set to true when the player guesses incorrectly elsemissedletters missedletters guess this is the start of the else-block rememberthe code in this block will execute if the condition was false but which conditionto find outpoint your finger at the start of the else keyword post questions to
7,559
and move it straight up like in figure - you'll see that the else keyword' indentation is the same as the if keyword' indentation on line figure - the else statement is matched with the if statement at the same indentation so if the condition on line (guess in secretwordwas falsethen the execution moves into this else-block wrongly guessed letters are concatenated to the missedletters string on line this is like what line did for letters the player guessed correctly check if player has guessed too many times and lost if len(missedletters=len(hangmanpics displayboard(hangmanpicsmissedletterscorrectletterssecretword print('you have run out of guesses!\nafter str(len(missedletters)missed guesses and str(len(correctletters)correct guessesthe word was "secretword '"' gameisdone true each time the player guesses wrongthe code concatenates the wrong letter to the string in missedletters so the length of missedletters (orin codelen(missedletters)is also the number of wrong guesses the hangmanpics list has ascii art strings so when len(missedlettersequals you know the player has lost because the hangman picture will be finished rememberhangmanpics[ is the first item in the listand hangmanpics[ is the last one sowhen the length of the missedletters string is equal to len(hangmanpics (that is )the player has run out of guesses line prints the secret word and line sets the gameisdone variable is set to true
7,560
done ask the player if they want to play again (but only if the game is if gameisdoneif playagain()missedletters 'correctletters 'gameisdone false secretword getrandomword(wordsif the player won or lost after guessing their letterthe game should ask the player if they want to play again the playagain(function handles getting yes or no from the playerso it is called on line if the player does want to play againthe values in missedletters and correctletters must be reset to blank stringsgameisdone to falseand new secret word stored in secretword this way when the execution loops back to the beginning of the while loop on line the board will be back to fresh game elsebreak if the player did not type in something that began with "ywhen asked if they wanted to play againthen line ' condition would be false and the else-block executes the break statement causes the execution to jump to the first instruction after the loop but because there are no more instructions after the loopthe program terminates summary this has been long and you've been introduced to several new concepts but hangman has been our most advanced game yet as your games get more and more complexit'll be good idea to sketch out flow chart on paper of what happens in your program lists are values that can contain other values methods are functions specific to data type lists have append(and reverse(methods strings have lower()upper()split()startswith()and endswith(methods you'll learn about many more data types and methods in the rest of this book the for loop is loop that iterates over the items in listunlike while loop which iterates as long as condition is true the elif statement lets you add an "or else ifclause to the middle of your if-else statements the del statement can delete variables or items inside lists post questions to
7,561
/ extending hangman topics covered in this the dictionary data type key-value pairs the keys(and values(dictionary methods multiple variable assignment the hangman is much bigger than the dragon realm programbut it' is also more sophisticated it really helps to make flow chart or small sketch to remember how you want everything to work now that you've created basic hangman gamelet' look at some ways you can extend it with new features after you've played hangman few timesyou might think that six guesses aren' enough to get many of the words you can easily give the player more guesses by adding more multi-line strings to the hangmanpics list save your hangman py program as hangman pythen add the following instructions ==========''''' +---- [ /| ==========''''' +---- [ /| =========='''there are two new multi-line strings to the hangmanpics listone with the hangman' left ear drawnand the other with both ears drawn because the program will tell the player they have lost on line based on len(missedletters=len(hangmanpics this is the only change you must make the rest of the program works with the new hangmanpics list just fine
7,562
you can also change the list of words by changing the words on line instead of animalsyou could have colors words 'red orange yellow green blue indigo violet white black brownsplit(or shapes words 'square triangle rectangle circle ellipse rhombus trapezoid chevron pentagon hexagon septagon octagonsplit(or fruits words 'apple orange lemon lime pear watermelon grape grapefruit cherry banana cantaloupe mango strawberry tomatosplit(dictionaries with some modificationyou can change the code so that the hangman game uses sets of wordssuch as animalcolorshapeor fruit the program can tell the player which set (animalcolorshapeor fruitthe secret word is from to make this changeyou will need new data type called dictionary dictionary is collection of values like list is but instead of accessing the items in the dictionary with an integer indexyou can access them with an index of any data type for dictionariesthese indexes are called keys dictionaries use and curly braces instead of and square brackets try entering the following into the interactive shellspam {'hello':'hello therehow are you?' :'bacon''eggs': the values between the curly braces are key-value pairs the keys are on the left of the colon and the key' values are on the right you can access the values like items in lists by using the key try entering the following into the interactive shellspam {'hello':'hello therehow are you?' :'bacon''eggs': spam['hello''hello therehow are you?spam[ 'baconspam[eggs post questions to
7,563
instead of putting an integer between the square bracketsyou can usesaya string key this will evaluate to the value for that key getting the size of dictionaries with len(you can get the number of key-value pairs in the dictionary with the len(function try entering the following into the interactive shellstuff {'hello':'hello therehow are you?' :'bacon''spam': len(stuff the difference between dictionaries and lists dictionaries can have keys of any data typenot just strings but rememberbecause and ' are different valuesthey will be different keys try entering this into the interactive shellspam {' ':' string' :'an integer'spam[ 'an integerspam[' '' stringthe keys in dictionaries can also be looped over using for loop try entering the following into the interactive shell favorites {'fruit':'apples''animal':'cats''number': for in favoritesprint(kfruit number animal for in favoritesprint(favorites[ ]apples cats dictionaries are different from lists because the values inside them are unordered the first item in list named liststuff would be liststuff[ but there' no "firstitem in dictionarybecause dictionaries do not have any sort of order try entering the following into the interactive shellfavorites {'fruit':'apples''number': 'animal':'cats'
7,564
favorites {'animal':'cats'favorites =favorites true 'number': 'fruit':'apples'the expression favorites =favorites evaluates to true because dictionaries are unordered and considered equal if they have the same key-value pairs in them meanwhilelists are orderedso two lists with the same values in different order are not equal to each other try entering this into the interactive shelllistfavs ['apples''cats' listfavs ['cats' 'apples'listfavs =listfavs false dictionaries have two useful methodskeys(and values(these will return values of type called dict_keys and dict_valuesrespectively much like range objectsvalues of those data types are returned by the list(function try entering the following into the interactive shellfavorites {'fruit':'apples''animal':'cats''number': list(favorites keys()['fruit''number''animal'list(favorites values()['apples' 'cats'sets of words for hangman let' change the code in the hangman game to support different sets of secret words firstreplace the value assigned to words with dictionary whose keys are strings and values are lists of strings the string method split(will return list of strings with one word each words {'colors':'red orange yellow green blue indigo violet white black brownsplit() 'shapes':'square triangle rectangle circle ellipse rhombus trapezoid chevron pentagon hexagon septagon octagonsplit() 'fruits':'apple orange lemon lime pear watermelon grape grapefruit cherry banana cantaloupe mango strawberry tomatosplit() 'animals':'bat bear beaver cat cougar crab deer dog donkey duck eagle fish frog goat leech lion lizard monkey moose mouse otter owl panda python rabbit rat shark sheep skunk squid tiger turkey turtle weasel whale wolf wombat zebrasplit()lines to are across multiple lines in the source codebut they are still one assignment statement the instruction doesn' end until the final curly brace on line post questions to
7,565
the random choice(function the choice(function in the random module takes list argument and returns random value from it this is similar to the what the previous getrandomword(function did you'll use random choice(in the new version of the getrandomword(function to see how the random choice(function workstry entering the following into the interactive shellimport random random choice(['cat''dog''mouse']'mouserandom choice(['cat''dog''mouse']'catrandom choice([ ] random choice([ ] change the getrandomword(function so that its parameter will be dictionary of lists of stringsinstead of just list of strings here is what the function originally looked like def getrandomword(wordlist) this function returns random string from the passed list of strings wordindex random randint( len(wordlist return wordlist[wordindexchange the code in this function so that it looks like this def getrandomword(worddict) this function returns random string from the passed dictionary of lists of stringsand the key also firstrandomly select key from the dictionary wordkey random choice(list(worddict keys()) secondrandomly select word from the key' list in the dictionary wordindex random randint( len(worddict[wordkey] return [worddict[wordkey][wordindex]wordkeythe name of the wordlist parameter is changed to worddict to be more descriptive now instead of choosing random word from list of stringsfirst the function chooses random key in the worddict dictionary by calling random choice(
7,566
and instead of returning the string wordlist[wordindex]the function returns list with two items the first item is worddict[wordkey][wordindexthe second item is wordkey evaluating dictionary of lists the worddict[wordkey][wordindexexpression on line may look complicatedbut it is just an expression you can evaluate one step at time like anything else firstimagine that wordkey had the value 'fruits(which was chosen on line and wordindex has the value (chosen on line here is how worddict[wordkey][wordindexwould evaluateworddict[wordkey][wordindexv worddict['fruits'][wordindexv ['apple''orange''lemon''lime''pear''watermelon''grape''grapefruit''cherry''banana''cantaloupe''mango''strawberry''tomato'][wordindexv ['apple''orange''lemon''lime''pear''watermelon''grape''grapefruit''cherry''banana''cantaloupe''mango''strawberry''tomato'][ 'watermelonin the above casethe item in the list this function returns would be the string 'watermelon(remember that indexes start at so [ refers to the th item in the listnot the th because the getrandomword(function now returns list of two items instead of stringsecretword will be assigned listnot string you can assign these two items into two separate variables using multiple assignment this is explained next multiple assignment multiple assignment is shortcut to specify multiple variablesseparated by commason the left side of an assignment statement try entering the following into the interactive shellabc ['apples''cats' 'applesb 'catsc post questions to
7,567
the above example is equivalent to the following assignment statementsa ['apples''cats' ][ ['apples''cats' ][ ['apples''cats' ][ you must put the same number of variables on the left side of the assignment operator as there are items in the list on the right side python will automatically assign the first item' value in the list to the first variablethe second item' value to the second variableand so on but if you do not have the same number of variables and itemsthe python interpreter will give you an error abcd ['apples''cats' 'hello'traceback (most recent call last)file ""line in abcd ['apples''cats' 'hello'valueerrortoo many values to unpack abcd ['apples''cats'traceback (most recent call last)file ""line in abc ['apples''cats'valueerrorneed more than values to unpack change your code in hangman on line and to use multiple assignment with the return value of getrandomword() correctletters ' secretwordsecretkey getrandomword(words gameisdone false gameisdone false secretwordsecretkey getrandomword(words elseprinting the word category for the player the last change you'll make is to tell the player which set of words they are trying to guess this waywhen the player plays the game they will know if the secret word is an animalcolorshapeor fruit add this line of code after line here is the original code while true displayboard(hangmanpicsmissedletterscorrectletterssecretwordadd the line so your program looks like this
7,568
while true print('the secret word is in the setsecretkey displayboard(hangmanpicsmissedletterscorrectletterssecretwordnow you're done with the changes to the hangman program instead of just single list of stringsthe secret word is chosen from many different lists of strings the program also tells the player which set of words the secret word is from try playing this new version you can easily change the words dictionary on line to include more sets of words summary we're done with hangman even after you've finished writing gameyou can always add more features after you learn more about python programming dictionaries are similar to lists except that they can use any type of value for an indexnot just integers the indexes in dictionaries are called keys multiple assignment is shortcut to assign multiple variables the values in list hangman was fairly advanced compared to the previous games in this book but at this pointyou know most of the basic concepts in writing programsvariablesloopsfunctionsand python' data types such as lists and dictionaries the later programs in this book will still be challenge to masterbut you have finished the steepest part of the climb post questions to
7,569
tic tac toe topics covered in this artificial intelligence list references short-circuit evaluation the none value this features tic tac toe game against simple artificial intelligence an artificial intelligence (or aiis computer program that can intelligently respond to the player' moves this game doesn' introduce any complicated new concepts the artificial intelligence that plays tic tac toe is really just few lines of code two people play tic tac toe with paper and pencil one player is and the other player is players take turns placing their or if player gets three of their marks on the board in rowcolumn or one of the two diagonalsthey win when the board fills up with neither player winningthe game ends in draw this doesn' introduce many new programming concepts it makes use of our existing programming knowledge to make an intelligent tic tac toe player let' get started by looking at sample run of the program the player makes their move by entering the number of the space they want to go these numbers are in the same places as the number keys on your keyboard' keypad (see figure - sample run of tic tac toe welcome to tic tac toedo you want to be or ox the computer will go first
7,570
what is your next move( - what is your next move( - what is your next move( - the computer has beaten youyou lose do you want to play again(yes or nono post questions to
7,571
source code of tic tac toe in new file editor windowtype in the following source code and save it as tictactoe py then run the game by pressing tictactoe py tic tac toe import random def drawboard(board) this function prints out the board that it was passed "boardis list of strings representing the board (ignore index print(|' print(board[ board[ board[ ] print(|' print('' print(|' print(board[ board[ board[ ] print(|' print('' print(|' print(board[ board[ board[ ] print(|' def inputplayerletter() lets the player type which letter they want to be returns list with the player' letter as the first itemand the computer' letter as the second letter ' while not (letter ='xor letter =' ') print('do you want to be or ?' letter input(upper( the first element in the list is the player' letterthe second is the computer' letter if letter =' ' return [' '' ' else return [' '' ' def whogoesfirst() randomly choose the player who goes first if random randint( =
7,572
return 'computer else return 'player def playagain() this function returns true if the player wants to play againotherwise it returns false print('do you want to play again(yes or no)' return input(lower(startswith(' ' def makemove(boardlettermove) board[moveletter def iswinner(bole) given board and player' letterthis function returns true if that player has won we use bo instead of board and le instead of letter so we don' have to type as much return ((bo[ =le and bo[ =le and bo[ =leor across the top (bo[ =le and bo[ =le and bo[ =leor across the middle (bo[ =le and bo[ =le and bo[ =leor across the bottom (bo[ =le and bo[ =le and bo[ =leor down the left side (bo[ =le and bo[ =le and bo[ =leor down the middle (bo[ =le and bo[ =le and bo[ =leor down the right side (bo[ =le and bo[ =le and bo[ =leor diagonal (bo[ =le and bo[ =le and bo[ =le)diagonal def getboardcopy(board) make duplicate of the board list and return it the duplicate dupeboard [ for in board dupeboard append( return dupeboard def isspacefree(boardmove) return true if the passed move is free on the passed board return board[move= def getplayermove(board) let the player type in their move move while move not in ' split(or not isspacefree(boardint(move)) print('what is your next move( - )'post questions to
7,573
move input( return int(move def chooserandommovefromlist(boardmoveslist) returns valid move from the passed list on the passed board returns none if there is no valid move possiblemoves [ for in moveslist if isspacefree(boardi) possiblemoves append( if len(possiblemoves! return random choice(possiblemoves else return none def getcomputermove(boardcomputerletter) given board and the computer' letterdetermine where to move and return that move if computerletter =' ' playerletter ' else playerletter ' here is our algorithm for our tic tac toe ai firstcheck if we can win in the next move for in range( ) copy getboardcopy(board if isspacefree(copyi) makemove(copycomputerletteri if iswinner(copycomputerletter) return check if the player could win on their next moveand block them for in range( ) copy getboardcopy(board if isspacefree(copyi) makemove(copyplayerletteri if iswinner(copyplayerletter) return try to take one of the cornersif they are free move chooserandommovefromlist(board[ ] if move !none return move try to take the centerif it is free
7,574
if isspacefree(board ) return move on one of the sides return chooserandommovefromlist(board[ ] def isboardfull(board) return true if every space on the board has been taken otherwise return false for in range( ) if isspacefree(boardi) return false return true print('welcome to tic tac toe!' while true reset the board theboard [' playerlettercomputerletter inputplayerletter( turn whogoesfirst( print('the turn will go first ' gameisplaying true while gameisplaying if turn ='player' player' turn drawboard(theboard move getplayermove(theboard makemove(theboardplayerlettermove if iswinner(theboardplayerletter) drawboard(theboard print('hoorayyou have won the game!' gameisplaying false else if isboardfull(theboard) drawboard(theboard print('the game is tie!' break else turn 'computer else computer' turn move getcomputermove(theboardcomputerletterpost questions to
7,575
makemove(theboardcomputerlettermoveif iswinner(theboardcomputerletter)drawboard(theboardprint('the computer has beaten youyou lose 'gameisplaying false elseif isboardfull(theboard)drawboard(theboardprint('the game is tie!'break elseturn 'playerif not playagain()break designing the program figure - is what flow chart of tic tac toe could look like in the tic tac toe computer program the player chooses if they want to be or who takes the first turn is randomly chosen then the player and computer take turns making moves the boxes on the left side of the flow chart are what happens during the player' turn the right side shows what happens on the computer' turn after the player or computer makes movethe program checks if they won or caused tieand then the game switches turns after the game is overthe program asks the player if they want to play again
7,576
figure - flow chart for tic tac toe figure - the board is numbered like the keyboard' number pad post questions to
7,577
representing the board as data firstyou must figure out how to represent the board as data in variable on paperthe tic tac toe board is drawn as pair of horizontal lines and pair of vertical lineswith either an xoor empty space in each of the nine spaces in the programthe tic tac toe board is represented as list of strings each string will represent one of the nine spaces on the board to make it easier to remember which index in the list is for which spacethey will mirror the numbers on keyboard' number keypadas shown in figure - the strings will either be 'xfor the player'ofor the playeror single space for blank space so if list with ten strings was stored in variable named boardthen board[ would be the top-left space on the board board[ would be the center board[ would be the left side spaceand so on the program will ignore the string at index in the list the player will enter number from to to tell the game which space they want to move on game ai the ai needs to be able to look at board and decide which types of spaces it will move on to be clearwe will label three types of spaces on the tic tac toe boardcornerssidesand the center figure - is chart of what each space is figure - locations of the sidecornerand center places
7,578
the ai' smarts for playing tic tac toe will follow simple algorithm an algorithm is finite series of instructions to compute result single program can make use of several different algorithms an algorithm can be represented with flow chart the tic tac toe ai' algorithm will compute the best move to makeas shown in figure - the ai' algorithm will have the following steps firstsee if there' move the computer can make that will win the game if there istake that move otherwisego to step see if there' move the player can make that will cause the computer to lose the game if there ismove there to block the player otherwisego to step check if any of the corner spaces (spaces or are free if somove there if no corner piece is freethen go to step check if the center is free if somove there if it isn'tthen go to step move on any of the side pieces (spaces or there are no more stepsbecause if the execution reaches step the side spaces are the only spaces left this all takes place in the "get computer' move box on the flow chart in figure - you could add this information to the flow chart with the boxes in figure - figure - the five steps of the "get computer' movealgorithm the arrows leaving go to the "check if computer wonbox post questions to
7,579
this algorithm is implemented in the getcomputermove(function and the other functions that getcomputermove(calls the start of the program tic tac toe import random the first couple of lines are comment and importing the random module so you can call the randint(function printing the board on the screen def drawboard(board) this function prints out the board that it was passed "boardis list of strings representing the board (ignore index print(|' print(board[ board[ board[ ] print(|' print('' print(|' print(board[ board[ board[ ] print(|' print('' print(|' print(board[ board[ board[ ] print(|'the drawboard(function will print the game board represented by the board parameter remember that the board is represented as list of ten stringswhere the string at index is the mark on space on the tic tac toe boardand so on the string at index is ignored many of the game' functions will work by passing list of ten strings as the board be sure to get the spacing right in the stringsotherwise the board will look funny when printed on the screen here are some example calls (with an argument for boardto drawboard(and what the function would printdrawboard([''''' '' ''' ''' '
7,580
['' '' '''' ''''' [''''''''''letting the player be or def inputplayerletter() lets the player type which letter they want to be returns list with the player' letter as the first itemand the computer' letter as the second letter ' while not (letter ='xor letter =' ') print('do you want to be or ?' letter input(upper(post questions to
7,581
the inputplayerletter(function asks if the player wants to be or it will keep asking the player until the player types in an or line automatically changes the string returned by the call to input(to uppercase letters with the upper(string method the while loop' condition contains parentheseswhich means the expression inside the parentheses is evaluated first if the letter variable was set to ' 'the expression would evaluate like thisnot (letter ='xor letter =' ' not (' ='xor ' =' ' not true or falsev not (truev not true false if letter has the value 'xor ' 'then the loop' condition is false and lets the program execution continue past the while-block the first element in the list is the player' letterthe second is the computer' letter if letter =' ' return [' '' ' else return [' '' 'this function returns list with two items the first item (the string at index is the player' letterand the second item (the string at index is the computer' letter these if-else statements chooses the appropriate list to return deciding who goes first def whogoesfirst() randomly choose the player who goes first if random randint( = return 'computer else return 'player
7,582
the whogoesfirst(function does virtual coin flip to determine whether the computer or the player goes first the coin flip is in calling random randint( if this function call returns the whogoesfirst(function returns the string 'computerotherwisethe function returns the string 'playerthe code that calls this function will use the return value to know who will make the first move of the game asking the player to play again def playagain() this function returns true if the player wants to play againotherwise it returns false print('do you want to play again(yes or no)' return input(lower(startswith(' 'the playagain(function asks the player if they want to play another game the function returns true if the player types in 'yes''yes'' 'or anything that begins with the letter for any other responsethe function returns false this function is identical to the one in the hangman game placing mark on the board def makemove(boardlettermove) board[moveletter the makemove(function is simple and only one line the parameters are list with ten strings named boardone of the player' letters (either 'xor ' 'named letterand place on the board where that player wants to go (which is an integer from to named move but wait second this code seems to change one of the items in the board list to the value in letter but because this code is in functionthe board parameter will be forgotten when the function returns shouldn' the change to board be forgotten as wellactuallythis isn' the case this is because lists are special when you pass them as arguments to functions you are actually passing reference of the list and not the list itself let' learn about the difference between lists and references to lists references try entering the following into the interactive shellspam cheese spam post questions to
7,583
spam spam cheese these results make sense from what you know so far you assign to the spam variableand then assign the value in spam and to the variable cheese when you later overwrite spam to this doesn' affect the value in cheese this is because spam and cheese are different variables that store different values but lists don' work this way when you assign list to variable with the signyou are actually assigning list reference to the variable reference is value that points to some bit of data here is some code that will make this easier to understand type this into the interactive shellspam [ cheese spam cheese[ 'hello!spam [ 'hello!' cheese [ 'hello!' this looks odd the code only changed the cheese listbut it seems that both the cheese and spam lists have changed this is because the spam variable does not contain the list value itselfbut rather spam contains reference to the list as shown in figure - the actual list itself is not contained in any variablebut rather exists outside of them figure - variables don' store listsbut rather references to lists
7,584
notice that cheese spam copies the list reference in spam to cheeseinstead of copying the list value itself now both spam and cheese store reference that refers to the same list value but there is only one list the list was not copiedthe reference to the list was copied figure - shows this copying figure - two variables store two references to the same list so the cheese[ 'hello!line changes the same list that spam refers to this is why spam seems to have the same list value that cheese does they both have references that refer to the same listas shown in figure - figure - changing the list changes all variables with references to that list post questions to
7,585
if you want spam and cheese to store two different listsyou have to create two different lists instead of copying referencespam [ cheese [ in the above examplespam and cheese have two different lists stored in them (even though these lists are identical in contentnow if you modify one of the listsit won' affect the other because spam and cheese have references to two different listsspam [ cheese [ cheese[ 'hello!spam [ cheese [ 'hello!' figure - shows how the two references point to two different lists figure - two variables each storing references to two different lists dictionaries also work the same way variables don' store dictionariesthey store references to dictionaries
7,586
using list references in makemove(let' go back to the makemove(function def makemove(boardlettermove) board[moveletter when list value is passed for the board parameterthe function' local variable is really copy of the reference to the listnot copy of the list but copy of the reference still refers to the same list the original reference refers so any changes to board in this function will also happen to the original list even though board is local variablethe makemove(function modifies the original list the letter and move parameters are copies of the string and integer values that you pass since they are copies of valuesif you modify letter or move in this functionthe original variables you used when you called makemove(aren' modified checking if the player has won def iswinner(bole) given board and player' letterthis function returns true if that player has won we use bo instead of board and le instead of letter so we don' have to type as much return ((bo[ =le and bo[ =le and bo[ =leor across the top (bo[ =le and bo[ =le and bo[ =leor across the middle (bo[ =le and bo[ =le and bo[ =leor across the bottom (bo[ =le and bo[ =le and bo[ =leor down the left side (bo[ =le and bo[ =le and bo[ =leor down the middle (bo[ =le and bo[ =le and bo[ =leor down the right side (bo[ =le and bo[ =le and bo[ =leor diagonal (bo[ =le and bo[ =le and bo[ =le)diagonal lines to in the iswinner(function are actually one long return statement the bo and le names are shortcuts for the board and letter parameters these shorter names mean you have less to type in this function rememberpython doesn' care what you name your variables there are eight possible ways to win at tic tac toe you can have line across the topmiddleand bottom rows or you can have line down the leftmiddleor right columns or you can have line over either of the two diagonals post questions to
7,587
note that each line of the condition checks if the three spaces are equal to the letter provided (combined with the and operatorand you use the or operator to combine the eight different ways to win this means only one of the eight ways must be true in order for us to say that the player who owns letter in le is the winner let' pretend that le is 'oand bo is ['' '' '' ''' ''' '''the board looks like thisx here is how the expression after the return keyword on line would evaluate top return ((bo[ =le and bo[ =le and bo[ =leor across the (bo[ =le and bo[ =le and bo[ =leor across the middle (bo[ =le and bo[ =le and bo[ =leor across the bottom (bo[ =le and bo[ =le and bo[ =leor down the left side (bo[ =le and bo[ =le and bo[ =leor down the middle (bo[ =le and bo[ =le and bo[ =leor down the right side (bo[ =le and bo[ =le and bo[ =leor diagonal (bo[ =le and bo[ =le and bo[ =le)diagonal first python will replace the variables bo and le with the value inside of themreturn ((' ='oand ='oand =' 'or (='oand ' ='oand =' 'or (' ='oand ' ='oand ' =' 'or (' ='oand ='oand ' =' 'or (='oand ' ='oand ' =' 'or (='oand ='oand ' =' 'or (' ='oand ' ='oand ' =' 'or (='oand ' ='oand ' =' ')nextpython will evaluate all those =comparisons inside the parentheses to boolean valuereturn ((false and false and falseor
7,588
(false and false and falseor (true and true and trueor (false and false and trueor (false and false and trueor (false and false and trueor (false and false and trueor (false and false and true)then the python interpreter will evaluate all those expressions inside the parenthesesreturn ((falseor (falseor (trueor (falseor (falseor (falseor (falseor (false)since now there' only one value inside the parenthesesyou can get rid of themreturn (false or false or true or false or false or false or false or falsenow evaluate the expression that is connecter by all those or operatorsreturn (trueonce againget rid of the parenthesesand you are left with one valuereturn true so given those values for bo and lethe expression would evaluate to true this is how the program can tell if one of the players has won the game duplicating the board data def getboardcopy(board)post questions to
7,589
make duplicate of the board list and return it the duplicate dupeboard [for in boarddupeboard append(ireturn dupeboard the getboardcopy(function is here so that you can easily make copy of given -string list that represents tic tac toe board in the game there are times that you'll want the ai algorithm to make temporary modifications to temporary copy of the board without changing the original board in that casecall this function to make copy of the board' list the new list is created on line with the blank list brackets [but the list stored in dupeboard on line is just an empty list the for loop will iterate over the board parameterappending copy of the string values in the original board to the duplicate board finallyafter the loopdupeboard is returned the getboardcopy(function builds up copy of the original board and returning reference to this new board in dupeboardand not the original one in board checking if space on the board is free def isspacefree(boardmove) return true if the passed move is free on the passed board return board[move=this is simple function thatgiven tic tac toe board and possible movewill return if that move is available or not remember that free spaces on the board lists are marked as single space string if the item at the space' index is not equal tothen the space is taken letting the player enter their move def getplayermove(board) let the player type in their move move while move not in ' split(or not isspacefree(boardint(move)) print('what is your next move( - )' move input( return int(move
7,590
the getplayermove(function asks the player to enter the number for the space they want to move on the loop makes sure the execution does not continue until the player has entered an integer from to it also checks that the space entered isn' already takengiven the tic tac toe board passed to the function for the board parameter the two lines of code inside the while loop simply ask the player to enter number from to the condition on line is true if either of the expressions on the left or right side of the or operator is true the expression on the left side checks if the player' move is equal to ' '' '' 'and so on up to ' by creating list with these strings (with the split(methodand checking if move is in this list ' split(evaluates to [' '' '' '' '' '' '' '' '' ']but the former easier to type the expression on the right side checks if the move that the player entered is free space on the board it checks this by calling the isspacefree(function remember that isspacefree(will return true if the move you pass is available on the board note that isspacefree(expects an integer for moveso the int(function returns an integer form of move the not operators are added to both sides so that the condition is true when either of these requirements are unfulfilled this will cause the loop to ask the player again and again until they enter proper move finallyline returns the integer form of whatever move the player entered remember that input(returns stringsso the int(function is called to return an integer form of the string short-circuit evaluation you may have noticed there' possible problem in the getplayermove(function what if the player typed in 'zor some other non-integer stringthe expression move not in ' split(on the left side of or would return false as expectedand then python would evaluate the expression on the right side of the or operator but calling int(' 'would cause an error python gives this error because the int(function can only take strings of number characterslike ' or ' 'not strings like 'zas an example of this kind of errortry entering this into the interactive shellint(' ' int(' 'traceback (most recent call last)post questions to
7,591
file ""line in int(' 'valueerrorinvalid literal for int(with base 'zbut when you play the tic tac toe game and try entering 'zfor your movethis error doesn' happen the reason is because the while loop' condition is being short-circuited short-circuiting means is that since the part on the left side of the or keyword (move not in ' split()evaluates to truethe python interpreter knows that the entire expression will evaluate to true it doesn' matter if the expression on the right side of the or keyword evaluates to true or falsebecause only one value on the side of the or operator needs to be true think about itthe expression true or false evaluates to true and the expression true or true also evaluates to true if the value on the left side is trueit doesn' matter what the value is on the right sidefalse and >always evaluates to false true or >always evaluates to true so python stops checking the rest of the expression and doesn' even bother evaluating the not isspacefree(boardint(move)part this means the int(and the isspacefree(functions are never called as long as move not in ' split(is true this works out well for the programbecause if the right side is true then move isn' string in number form that would cause int(to give us an error the only times move not in ' split(evaluates to false are when move isn' single-digit string in that casethe call to int(would not give us an error an example of short-circuit evaluation here' short program that gives good example of short-circuiting try entering the following into the interactive shelldef returnstrue()print('returnstrue(was called 'return true def returnsfalse()print('returnsfalse(was called 'return false returnstrue(returnstrue(was called
7,592
true returnsfalse(returnsfalse(was called false when returnstrue(is calledit prints 'returnstrue(was called and then also displays the return value of returnstrue(the same goes for returnsfalse(now try entering the following into the interactive shell returnsfalse(or returnstrue(returnsfalse(was called returnstrue(was called true returnstrue(or returnsfalse(returnstrue(was called true the first part makes sensethe expression returnsfalse(or returnstrue(calls both of the functionsso you see both of the printed messages but the second expression only shows 'returnstrue(was called but not 'returnsfalse(was called this is because python did not call returnsfalse(at all since the left side of the or operator is trueit doesn' matter what returnsfalse(returns and python doesn' bother calling it the evaluation was short-circuited the same applies for the and operator try entering the following into the interactive shellreturnstrue(and returnstrue(returnstrue(was called returnstrue(was called true returnsfalse(and returnsfalse(returnsfalse(was called false if the left side of the and operator is falsethen the entire expression is false it doesn' matter whether the right side of the and operator is true or falseso python doesn' bother evaluating it both false and true and false and false evaluate to falseso python short-circuits the evaluation choosing move from list of moves def chooserandommovefromlist(boardmoveslist) returns valid move from the passed list on the passed board post questions to
7,593
returns none if there is no valid move possiblemoves [for in moveslistif isspacefree(boardi)possiblemoves append(ithe chooserandommovefromlist(function is useful for the ai code later in the program the board parameter is list of strings that represents tic tac toe board the second parameter moveslist is list of integers of possible spaces from which to choose for exampleif moveslist is [ ]that means chooserandommovefromlist(should return the integer for one of the corner spaces howeverchooserandommovefromlist(will first check that the space is valid to make move on the possiblemoves list starts as blank list the for loop will iterate over moveslist the moves that cause isspacefree(to return true are added to possiblemoves with the append(method if len(possiblemoves! return random choice(possiblemoveselsereturn none at this pointthe possiblemoves list has all of the moves that were in moveslist that are also free spaces if the list isn' emptythen there' at least one possible move that can be made on the board but this list could be empty for exampleif moveslist was [ but the board represented by the board parameter had all the corner spaces already takenthe possiblemoves list would be [in that caselen(possiblemoveswill evaluate to and the function returns the value none this next section explains the none value the none value the none value is value that represents the lack of value none is the only value of the data type nonetype it can be useful to use the none value when you need value that means "does not existor "none of the abovefor examplesay you had variable named quizanswer which holds the user' answer to some true-false pop quiz question the variable could hold true or false for the user' answer you could set quizanswer to none if the user skipped the question and didn' answer it using none would be better because otherwise it may look like the user answered the question when they didn'
7,594
functions that return by reaching the end of the function (and not from return statementhave none for return value the none value is written without quotes and with capital "nand lowercase "oneas side notenone will not be displayed in the interactive shell like other values will be 'this is string value 'this is string value none functions that don' seem to return anything actually return the none value for exampleprint(returns nonespam print('hello world!'hello worldspam =none true creating the computer' artificial intelligence def getcomputermove(boardcomputerletter) given board and the computer' letterdetermine where to move and return that move if computerletter =' ' playerletter ' else playerletter 'xthe getcomputermove(function contains the ai' code the first argument is tic tac toe board for the board parameter the second argument is letter for the computer either 'xor 'oin the computerletter parameter the first few lines simply assign the other letter to variable named playerletter this way the same code can be used whether the computer is or the function will returns an integer from to representing the computer' move remember how the tic tac toe ai algorithm worksfirstsee if there' move the computer can make that will win the game if there istake that move otherwisego to the second step post questions to
7,595
secondsee if there' move the player can make that will cause the computer to lose the game if there isthe computer should move there to block the player otherwisego to the third step thirdcheck if any of the corner spaces (spaces or are free if no corner space is freethen go to the fourth step fourthcheck if the center is free if somove there if it isn'tthen go to the fifth step fifthmove on any of the side pieces (spaces or there are no more stepsbecause if the execution has reached this step then the side spaces are the only spaces left the computer checks if it can win in one move here is our algorithm for our tic tac toe aifirstcheck if we can win in the next move for in range( )copy getboardcopy(boardif isspacefree(copyi)makemove(copycomputerletteriif iswinner(copycomputerletter)return more than anythingif the computer can win in the next movethe computer should make that winning move immediately the for loop that starts on line iterates over every possible move from to the code inside the loop will simulate what would happen if the computer made that move the first line in the loop (line makes copy of the board list this is so the simulated move inside the loop doesn' modify the real tic tac toe board stored in the board variable the getboardcopy(returns an identical but separate board list value line checks if the space is free and if sosimulates making the move on the copy of the board if this move results in the computer winningthe function returns that move' integer if none of the spaces results in winningthe loop will finally end and the program execution continues to line the computer checks if the player can win in one move check if the player could win on their next moveand block them for in range( )copy getboardcopy(boardif isspacefree(copyi)
7,596
makemove(copyplayerletteriif iswinner(copyplayerletter)return nextthe code will simulate the human player moving on each of the spaces the code is similar to the previous loop except the player' letter is put on the board copy if the iswinner(function shows that the player would win with this movethen the computer will return that same move to block this from happening if the human player cannot win in one more movethe for loop will eventually finish and execution continues to line checking the cornercenterand side spaces (in that order try to take one of the cornersif they are free move chooserandommovefromlist(board[ ]if move !nonereturn move the call to chooserandommovefromlist(with the list of [ will ensure that it returns the integer for one of the corner spaces or if all the corner spaces are takenthe chooserandommovefromlist(function will return none and execution moves on to line try to take the centerif it is free if isspacefree(board )return if none of the corners are availableline moves on the center space if it is free if the center space isn' freethe execution moves on to line move on one of the sides return chooserandommovefromlist(board[ ]this code also makes call to chooserandommovefromlist()except you pass it list of the side spaces ([ ]this function won' return none because the side spaces are the only spaces that can possibly be left this ends the getcomputermove(function and the ai algorithm checking if the board is full def isboardfull(board) return true if every space on the board has been taken otherwise return false post questions to
7,597
for in range( )if isspacefree(boardi)return false return true the last function is isboardfull(this function returns true if the -string list board argument it was passed has an 'xor 'oin every index (except for index which is ignoredif there' at least one space in board that is set to single space then it will return false the for loop will let us check indexes through on the board list as soon as it finds free space on the board (that iswhen isspacefree(boardireturns truethe isboardfull(function will return false if execution manages to go through every iteration of the loopthen none of the spaces are free line will then execute return true the start of the game print('welcome to tic tac toe!'line is the first line that isn' inside of functionso it is the first line of code that executes when you run this program it greets the player while true reset the board theboard [' line ' while loop has true for the condition and will keep looping until the execution encounters break statement line sets up the main tic tac toe board in variable named theboard it is -string listwhere each string is single space rather than type out this full listline uses list replication it is shorter to type [' then [''''''''''deciding the player' mark and who goes first playerlettercomputerletter inputplayerletter(the inputplayerletter(function lets the player type in whether they want to be or the function returns -string listeither [' '' 'or [' '' 'the multiple assignment trick will set playerletter to the first item in the returned list and computerletter to the second
7,598
turn whogoesfirst(print('the turn will go first 'gameisplaying true the whogoesfirst(function randomly decides who goes firstand returns either the string 'playeror the string 'computerand line tells the player who will go first the gameisplayer variable keeps track of whether the game is still being played or if someone has won or tied running the player' turn while gameisplayingline ' loop will keep going back and forth between the code for the player' turn and the computer' turnas long as gameisplaying is set to true if turn ='player'player' turn drawboard(theboardmove getplayermove(theboardmakemove(theboardplayerlettermovethe turn variable was originally set by the whogoesfirst(call on line it is set either to 'playeror 'computerif turn equals 'computer'then line ' condition is false and execution jumps to line line calls drawboard(and passes the theboard variable to print the tic tac toe board on the screen then the getplayermove(function lets the player type in their move (and also makes sure it is valid movethe makemove(function adds the player' or to theboard if iswinner(theboardplayerletter)drawboard(theboardprint('hoorayyou have won the game!'gameisplaying false now that the player has made their movethe computer should check if they have won the game with this move if the iswinner(function returns truethe if-block' code displays the winning board and prints message telling them they have won the gameisplaying variable is also set to false so that execution doesn' continue on to the computer' turn post questions to
7,599
elseif isboardfull(theboard)drawboard(theboardprint('the game is tie!'break if the player didn' win with their last movemaybe their move filled up the entire board and tied the game in this else-blockthe isboardfull(function returns true if there are no more moves to make in that casethe if-block starting at line displays the tied board and tell the player tie has occurred the execution breaks out of the while loop and jumps to line elseturn 'computerif the player hasn' won or tied the gamethen line sets the turn variable to 'computerso that it will execute the code for the computer' turn on the next iteration running the computer' turn if the turn variable wasn' 'playerfor the condition on line then it must be the computer' turn the code in this else-block is similar to the code for the player' turn elsecomputer' turn move getcomputermove(theboardcomputerlettermakemove(theboardcomputerlettermoveif iswinner(theboardcomputerletter)drawboard(theboardprint('the computer has beaten youyou lose 'gameisplaying false elseif isboardfull(theboard)drawboard(theboardprint('the game is tie!'break elseturn 'playerlines to are almost identical to the code for the player' turn on lines to the only difference is this the code uses the computer' letter and calls getcomputermove(if the game isn' won or tiedline sets turn to the player' turn there are no more lines of code inside the while loopso execution would jump back to the while statement on line