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 choosecav...
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 forg...
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 t...
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' pyt...
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 'ye...
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 va...
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 ide...
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 ...
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 t...
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 wh...
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(hav...
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 ...
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 r...
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 t...
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...
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 ...
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 int...
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 s...
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 ne...
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...
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 "p...
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 co...
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 sh...
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 l...
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 pla...
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 do...
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 ...
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 dis...
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'...
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 tige...
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(hangm...
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 p...
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 make...
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 th...
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...
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 ...
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 enteri...
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...
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!'whic...
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' th...
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 ...
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 li...
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(...
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 na...
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(i...
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 sp...
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...
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 secr...
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 va...
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...
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...
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 s...
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 l...
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 gues...
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-...
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 g...
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 e...
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 ...
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'...
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...
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 t...
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 s...
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 i...
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 o...
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...
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 ...
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 ...
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 n...
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 ...
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...
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 str...
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 figu...
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(bo...
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(pos...
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 i...
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 wi...
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 ...
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 variable...
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 oth...
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...
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 wi...
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 (falseo...
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 temporar...
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 p...
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 (m...
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 ...
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 intege...
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...
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...
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...
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 ...
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 someo...
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 displ...