id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
7,000 | simple substitution cipher the simple substitution cipher substitutes one letter for another since there are possible substitutions for the letter possible substitutions for for cand so onthe total number of possible keys is or , , , , , , , , keysthat' far too many keys for even supercomputer to brute forceso the code-breaking method used in project "caesar hacker,can' be used against the simple cipher unfortunatelydevious attackers can take advantage of known weakness to break the code if you' like to learn more about ciphers and code breakingyou can read my book cracking codes with python (no starch press crackingcodes/ |
7,001 | when you run simplesubcipher pythe output will look like thissimple substitution cipherby al sweigart simple substitution cipher has one-to-one translation for each symbol in the plaintext and each symbol in the ciphertext do you want to ( )ncrypt or ( )ecrypte please specify the key to use or enter random to have one generated for you random the key is wnomtrcehdxbfvslkagzipyjqu keep this secretenter the message to encrypt meet me by the rose bushes tonight the encrypted message isfttz ft nq zet asgt nigetg zsvhcez full encrypted text copied to clipboard simple substitution cipherby al sweigart simple substitution cipher has one-to-one translation for each symbol in the plaintext and each symbol in the ciphertext do you want to ( )ncrypt or ( )ecryptd please specify the key to use wnomtrcehdxbfvslkagzipyjqu enter the message to decrypt fttz ft nq zet asgt nigetg zsvhcez the decrypted message ismeet me by the rose bushes tonight full decrypted text copied to clipboard how it works the position of each of the key' letters corresponds to the letter of the alphabet at that same positiona mno vwx wn figure - how the letters of the alphabet encrypt with key that begins with wnom to decryptreplace letters at the bottom with the corresponding letters above them with this keythe letter encrypts to (and decrypts to )the letter encrypts to nand so on the letters and key variables are assigned to charsa and charsb (or the other way around if decryptingany message characters in charsa are substituted with the corresponding character in charsb to produce the final translated message """simple substitution cipherby al sweigart al@inventwithpython com simple substitution cipher has one-to-one translation for each symbol in the plaintext and each symbol in the ciphertext project # |
7,002 | view this code at tagsshortcryptographymath"" import random try import pyperclip pyperclip copies text to the clipboard except importerror pass if pyperclip is not installeddo nothing it' no big deal every possible symbol that can be encrypted/decrypted letters 'abcdefghijklmnopqrstuvwxyz def main() print('''simple substitution cipherby al sweigart simple substitution cipher has one-to-one translation for each symbol in the plaintext and each symbol in the ciphertext ''' let the user specify if they are encrypting or decrypting while truekeep asking until the user enters or print('do you want to ( )ncrypt or ( )ecrypt?' response input(''lower( if response startswith(' ') mymode 'encrypt break elif response startswith(' ') mymode 'decrypt break print('please enter the letter or ' let the user specify the key to use while truekeep asking until the user enters valid key print('please specify the key to use ' if mymode ='encrypt' print('or enter random to have one generated for you ' response input(''upper( if response ='random' mykey generaterandomkey( print('the key is {keep this secret!format(mykey) break else if checkkey(response) mykey response break let the user specify the message to encrypt/decrypt print('enter the message to {format(mymode) mymessage input('' perform the encryption/decryption if mymode ='encrypt' translated encryptmessage(mymessagemykey elif mymode ='decrypt' translated decryptmessage(mymessagemykeysimple substitution cipher |
7,003 | display the results print('the %sed message is:(mymode) print(translated try pyperclip copy(translated print('full %sed text copied to clipboard (mymode) except pass do nothing if pyperclip wasn' installed def checkkey(key) """return true if key is valid otherwise return false "" keylist list(key letterslist list(letters keylist sort( letterslist sort( if keylist !letterslist print('there is an error in the key or symbol set ' return false return true def encryptmessage(messagekey) """encrypt the message using the key "" return translatemessage(messagekey'encrypt' def decryptmessage(messagekey) """decrypt the message using the key "" return translatemessage(messagekey'decrypt' def translatemessage(messagekeymode) """encrypt or decrypt the message using the key "" translated ' charsa letters charsb key if mode ='decrypt' for decryptingwe can use the same code as encrypting we just need to swap where the key and letters strings are used charsacharsb charsbcharsa loop through each symbol in the message for symbol in message if symbol upper(in charsa encrypt/decrypt the symbol symindex charsa find(symbol upper() if symbol isupper() translated +charsb[symindexupper( else translated +charsb[symindexlower( else the symbol is not in lettersjust add it unchanged project # |
7,004 | translated +symbol return translated def generaterandomkey() """generate and return random encryption key "" key list(lettersget list from the letters string random shuffle(keyrandomly shuffle the list return 'join(keyget string from the list if this program was run (instead of imported)run the program if __name__ ='__main__' main(exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you delete or comment out random shuffle(keyon line and enter random for the key what happens if you extend the letters string on line to become 'abcdefghijklmnopqrstuvwxyz 'simple substitution cipher |
7,005 | sine message this program displays message of the user' choice in wavy pattern as the text scrolls up it accomplishes this effect with math sin()which implements the trigonometric sine wave function but even if you don' understand the maththis program is rather short and easy to copy |
7,006 | when you run sinemessage pythe output will look like thissine messageby al sweigart al@inventwithpython com (press ctrl- to quit what message do you want to display(max chars < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programmingi < programming--snip-how it works the math sin(function in python' math module takes an argumentwhich we'll call xand returns another number called the sine of several mathematical applications use the sine functionin our programits purpose is merely to create neat wave effect we pass variable named step to math sin(this variable starts at and increases by on each iteration of the main program loop we'll use the return value of math sin(to figure out how many spaces of padding we should print on either side of the user' message since math sin(returns floating point number between - and but the minimum amount of padding we want is zeronot negative valueline adds to the return value of math sin()making the effective range to we'll certainly need more than zero to two spacesso line multiplies this number by variable named multiplier to increase the amount of padding the product of this multiplication is the number of spaces of padding to add to the left side before printing the user' message sine message |
7,007 | program """sine messageby al sweigart al@inventwithpython com create sine-wavy message view this code at tagstinyartistic"" import mathshutilsystime get the size of the terminal window widthheight shutil get_terminal_size( we can' print to the last column on windows without it adding newline automaticallyso reduce the width by one width - print('sine messageby al sweigart al@inventwithpython com' print('(press ctrl- to quit )' print( print('what message do you want to display(max'width / 'chars )' while true message input('' if <len(message<(width / ) break print('message must be to'width / 'characters long ' step the "stepdetermines how far into the sine wave we are sine goes from - to so we need to change it by multiplier multiplier (width len(message) try while truemain program loop sinofstep math sin(step padding int((sinofstep multiplier print(padding message time sleep( step + (!try changing this to or except keyboardinterrupt sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change math sin(stepon line to math cos(step) what happens if you change math sin(stepon line to math sin( ) project # |
7,008 | sliding tile puzzle this classic puzzle relies on board with numbered tiles and one free space the objective is to slide the tiles until the numbers are in the correct ordergoing left to right and top to bottom tiles can only slideyou're not allowed to directly pick them up and rearrange them some versions of this puzzle toy feature scrambled images that form complete picture once solved more information about sliding tile puzzles can be found at en wikipedia org/wiki/sliding_puzzle |
7,009 | when you run slidingtilepuzzle pythe output will look like thissliding tile puzzleby al sweigart al@inventwithpython com use the wasd keys to move the tiles back into their original order press enter to begin ++++ ++++ ++++ ++++ ++++(wenter wasd (or quit)( (dw ++++ ++++ ++++ ++++ ++++ project # |
7,010 | enter wasd (or quit)( ( ( --snip-how it works the data structure that represents the sliding tile game board is list of lists the inner lists each represent one column of the board and contain strings for the numbered tiles (or the blank string to represent the blank spacethe getnewboard(function returns this list of lists with all tiles in their starting positions and the blank space in the lower-right corner python can swap the values in two variables with statement like ab ba the program uses this technique on lines to to swap the blank space and neighboring tile and simulate sliding numbered tile into the blank space the getnewpuzzle(function generates new puzzles by performing of these swaps randomly """sliding tile puzzleby al sweigart al@inventwithpython com slide the numbered tiles into the correct order view this code at tagslargegamepuzzle"" import randomsys blank notethis string is two spacesnot one def main() print('''sliding tile puzzleby al sweigart al@inventwithpython com use the wasd keys to move the tiles back into their original order ''' input('press enter to begin ' gameboard getnewpuzzle( while true displayboard(gameboard playermove askforplayermove(gameboard makemove(gameboardplayermove if gameboard =getnewboard() print('you won!' sys exit( def getnewboard() """return list of lists that represents new tile puzzle ""sliding tile puzzle |
7,011 | return [[' '' '' '' '][' '' '' '' '] [' '' '' '' '][' '' '' 'blank] def displayboard(board) """display the given board on the screen "" labels [board[ ][ ]board[ ][ ]board[ ][ ]board[ ][ ] board[ ][ ]board[ ][ ]board[ ][ ]board[ ][ ] board[ ][ ]board[ ][ ]board[ ][ ]board[ ][ ] board[ ][ ]board[ ][ ]board[ ][ ]board[ ][ ] boardtodraw "" ++++ {{{{ ++++ {{{{ ++++ {{{{ ++++ {{{{ ++++ ""format(*labels print(boardtodraw def findblankspace(board) """return an (xytuple of the blank space' location "" for in range( ) for in range( ) if board[ ][ =' return (xy def askforplayermove(board) """let the player select tile to slide "" blankxblanky findblankspace(board 'wif blanky ! else 'aif blankx ! else 'sif blanky ! else 'dif blankx ! else while true print(({})format( ) print('enter wasd (or quit)({}({}({})format(asd) response input(''upper( if response ='quit' project # |
7,012 | sys exit( if response in ( dreplace(''') return response def makemove(boardmove) """carry out the given move on the given board "" notethis function assumes that the move is valid bxby findblankspace(board if move =' ' board[bx][by]board[bx][by+ board[bx][by+ ]board[bx][by elif move =' ' board[bx][by]board[bx+ ][byboard[bx+ ][by]board[bx][by elif move =' ' board[bx][by]board[bx][by- board[bx][by- ]board[bx][by elif move =' ' board[bx][by]board[bx- ][byboard[bx- ][by]board[bx][by def makerandommove(board) """perform slide in random direction "" blankxblanky findblankspace(board validmoves [ if blanky ! validmoves append(' ' if blankx ! validmoves append(' ' if blanky ! validmoves append(' ' if blankx ! validmoves append(' ' makemove(boardrandom choice(validmoves) def getnewpuzzle(moves= ) """get new puzzle by making random slides from solved state "" board getnewboard( for in range(moves) makerandommove(board return board if this program was run (instead of imported)run the game if __name__ ='__main__' main(after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingcreate more difficult variant of the sliding tile puzzle sliding tile puzzle |
7,013 | create "solve automaticallymodewhich saves the current arrangement of the tiles and then attempts up to random moves and stops if they have solved the puzzle otherwisethe puzzle loads the saved state and attempts another random moves exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change getnewpuzzle(on line to getnewpuzzle( ) what happens if you change getnewpuzzle(on line to getnewpuzzle( ) what happens if you delete or comment out sys exit(on line project # |
7,014 | snail ace you won' be able to handle the fast-paced excitement of these racing snails but what they lack in speed they make up for in ascii-art cuteness each snail (represented by an character for the shell and for the two eyestalksmoves slowly but surely toward the finish line up to eight snailseach with custom namecan race each otherleaving slime trail in their wake this program is good for beginners |
7,015 | when you run snailrace pythe output will look like thissnail raceby al sweigart al@inventwithpython com @ <-snail how many snails will racemax enter snail # ' namealice enter snail # ' namebob enter snail # ' namecarol start alice @ bob @ carol @ --snip-finish how it works this program makes use of two data structuresstored in two variablessnailnames is list of strings of each snail' nameand snailprogress is dictionary whose keys are the snailsnames and whose values are integers representing how many spaces the snails have moved lines to read the data in these two variables to draw the snails at appropriate places on the screen """snail raceby al sweigart al@inventwithpython com fast-paced snail racing action view this code at tagsshortartisticbeginnergamemultiplayer"" import randomtimesys set up the constants max_num_snails max_name_length finish_line (!try modifying this number print('''snail raceby al sweigart al@inventwithpython com @ <-snail ''' project # |
7,016 | while truekeep asking until the player enters number print('how many snails will racemax:'max_num_snails response input('' if response isdecimal() numsnailsracing int(response if numsnailsracing <max_num_snails break print('enter number between and'max_num_snails enter the names of each snail snailnames [list of the string snail names for in range( numsnailsracing ) while truekeep asking until the player enters valid name print('enter snail #str( "' name:" name input('' if len(name= print('please enter name ' elif name in snailnames print('choose name that has not already been used ' else break the entered name is acceptable snailnames append(name display each snail at the start line print('\ print('start((finish_line len('start')'finish') print('|((finish_line len('|')'|') snailprogress { for snailname in snailnames print(snailname[:max_name_length] print('@ ' snailprogress[snailname time sleep( the pause right before the race starts while truemain program loop pick random snails to move forward for in range(random randint( numsnailsracing / )) randomsnailname random choice(snailnames snailprogress[randomsnailname+ check if snail has reached the finish line if snailprogress[randomsnailname=finish_line print(randomsnailname'has won!' sys exit( (!experimentadd cheat here that increases snail' progress if it has your name time sleep( (!experimenttry changing this value (!experimentwhat happens if you comment this line out print('\ snail race |
7,017 | display the start and finish linesprint('start((finish_line len('start')'finish')print('|((finish_line '|')display the snails (with name tags)for snailname in snailnamesspaces snailprogress[snailnameprint((spacessnailname[:max_name_length]print((snailprogress[snailname]'@ 'after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingadd random "speed boostthat launches the snail four spaces ahead instead of one add "sleep modethat snails can randomly enter during the race this mode causes them to stop for few turns and zzz to appear next to them add support for tiesin case snails reach the finish line at the same time exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change snailname[:max_name_lengthon line to snailnames[ ] what happens if you change print('@ 'on line to print(' @') project # |
7,018 | so ro ba pa bac an abacusalso called counting frameis calculating tool used in many cultures long before electronic calculators were invented figure - shows the japanese form of the abacuscalled soroban each wire represents place in positional numeral systemand the beads on the wire represent the digit at that place for examplea soroban with two beads moved over on the rightmost wire and three beads moved over on the second-to-rightmost wire would represent the number this program simulates soroban (the irony of using computer to simulate pre-computer computing tool is not lost on me |
7,019 | each column in the soroban represents different digit the rightmost column is the ones placethe column to its left is the tens placethe column to the left of that is the hundreds placeand so on the qwertyuioand keys along the top of your keyboard can increase the digit at their respective positionswhile the asdfghjkland keys will decrease them the beads on the virtual soroban will slide to reflect the current number you can also enter numbers directly the four beads below the horizontal divider are "earthbeadsand lifting them up against the divider counts as for that digit the bead above the horizontal divider is "heavenbeadand pulling it down against the divider counts as for that digitso pulling down one heaven bead and pulling up three earth beads in the tens column represents the number more information about abacuses and how to use them can be found at the program in action when you run soroban pythe output will look like thissoroban the japanese abacus by al sweigart al@inventwithpython com +================================ +================================ +== == == == == == == == == == ==+ - (enter number"quit"or stream of up/down letters pppiiiii project # |
7,020 | +================================ +== == == == == == == == == == ==+ - (enter number"quit"or stream of up/down letters --snip-how it works the displayabacus(function accepts number argument used to figure out where it should render beads on the abacus the soroban always has exactly possible locations for either 'obeads or '|rod segmentsas marked by the curly braces ({}in the multiline string on lines to another curly braces represent the digits of the number argument we need to create list of strings to fill in these curly bracesgoing from left to righttop to bottom the code in displayabacus(will populate hasbead list with true value to display 'obead and false value to display '|the first values in this list are for the top "heavenrow we'll put bead in this row if the column' digit is or since the heaven bead won' be in that row unless the digit for that column is to we add boolean values to hasbead for the remaining rows lines to use hasbead to create an abacuschar list that contains the actual 'oand '|strings when combined with numberlist on line the program forms chars list that populates the curly braces ({}for the multiline-string ascii art of the soroban """soroban japanese abacusby al sweigart al@inventwithpython com simulation of japanese abacus calculator tool more info at view this code at tagslargeartisticmathsimulation"" number_of_digits def main() print('soroban the japanese abacus' print('by al sweigart al@inventwithpython com' print( abacusnumber this is the number represented on the abacus soroban japanese abacus |
7,021 | project # while truemain program loop displayabacus(abacusnumberdisplaycontrols(commands input(''if commands ='quit'quit the programbreak elif commands isdecimal()set the abacus numberabacusnumber int(commandselsehandle increment/decrement commandsfor letter in commandsif letter =' 'abacusnumber + elif letter =' 'abacusnumber - elif letter =' 'abacusnumber + elif letter =' 'abacusnumber - elif letter =' 'abacusnumber + elif letter =' 'abacusnumber - elif letter =' 'abacusnumber + elif letter =' 'abacusnumber - elif letter =' 'abacusnumber + elif letter =' 'abacusnumber - elif letter =' 'abacusnumber + elif letter =' 'abacusnumber - elif letter =' 'abacusnumber + elif letter =' 'abacusnumber - elif letter =' 'abacusnumber + elif letter =' 'abacusnumber - elif letter =' 'abacusnumber + elif letter =' 'abacusnumber - elif letter =' 'abacusnumber + elif letter =';'abacusnumber - |
7,022 | the abacus can' show negative numbers if abacusnumber abacusnumber change any negative numbers to the abacus can' show numbers larger than if abacusnumber abacusnumber def displayabacus(number) numberlist list(str(numberzfill(number_of_digits) hasbead [contains true or false for each bead position top heaven row has bead for digits and for in range(number_of_digits) hasbead append(numberlist[iin ' ' bottom heaven row has bead for digits and for in range(number_of_digits) hasbead append(numberlist[iin ' ' st (topmostearth row has bead for all digits except for in range(number_of_digits) hasbead append(numberlist[iin ' ' nd earth row has bead for digits and for in range(number_of_digits) hasbead append(numberlist[iin ' ' rd earth row has bead for digits and for in range(number_of_digits) hasbead append(numberlist[iin ' ' th earth row has bead for digits and for in range(number_of_digits) hasbead append(numberlist[iin ' ' th earth row has bead for digits and for in range(number_of_digits) hasbead append(numberlist[iin ' ' th earth row has bead for digits and for in range(number_of_digits) hasbead append(numberlist[iin ' ' convert these true or false values into or characters abacuschar [ for ibeadpresent in enumerate(hasbead) if beadpresent abacuschar append(' ' else abacuschar append('|' draw the abacus with the /characters soroban japanese abacus |
7,023 | chars abacuschar numberlist print("" +================================ {{{{{{{{{{ {{{{{{{{{{ +================================ {{{{{{{{{{ {{{{{{{{{{ {{{{{{{{{{ {{{{{{{{{{ {{{{{{{{{{ {{{{{{{{{{ +=={}=={}=={}=={}=={}=={}=={}=={}=={}=={}==+""format(*chars) def displaycontrols() print(+ ' print(- ;' print('(enter number"quit"or stream of up/down letters )' if __name__ ='__main__' main(exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change abacusnumber on line to abacusnumber what happens if you change abacuschar append(' 'on line to abacuschar append('@') project # |
7,024 | sound mimic similar to the simon electronic toythis memorization game uses the third-party playsound module to play four different soundswhich correspond to the asdand keys on the keyboard as you successfully repeat the pattern the game gives youthe patterns get longer and longer how many sounds can you hold in your short-term memoryif you look at the codeyou'll see that the playsound playsound(function is passed the filename of the sound to play you can download the sound files from these urls |
7,025 | program more information about the playsound module can be found at module from the program in action when you run soundmimic pythe output will look like thissound mimicby al sweigart al@inventwithpython com try to memorize pattern of letters (each with its own soundas it gets longer and longer press enter to begin patterns enter the patterns correctpatterns enter the patternsf correctpatterns enter the patternsff correctpatterns --snip-how it works this program imports the playsound modulewhich can play sound files the module has one functionplaysound()to which you can pass the filename of wav or mp file to play on each round of the gamethe program appends randomly chosen letter (either asdor fto the pattern list and plays the sounds in this list as the pattern list grows longerso does the pattern of sound files the player must memorize """sound mimicby al sweigart al@inventwithpython com pattern-matching game with sounds try to memorize an increasingly longer and longer pattern of letters inspired by the electronic game simon view this code at tagsshortbeginnergame"" project # |
7,026 | download the sound files from these urls (or use your own) try import playsound except importerror print('the playsound module needs to be installed to run this' print('program on windowsopen command prompt and run:' print('pip install playsound' print('on macos and linuxopen terminal and run:' print('pip install playsound' sys exit( print('''sound mimicby al sweigart al@inventwithpython com try to memorize pattern of letters (each with its own sound as it gets longer and longer ''' input('press enter to begin ' pattern ' while true print('\ clear the screen by printing several newlines add random letter to the pattern pattern pattern random choice('asdf' display the pattern (and play their sounds) print('pattern'end='' for letter in pattern print(letterend='flush=true playsound playsound('soundletter wav' time sleep( add slight pause at the end print('\ clear the screen by printing several newlines let the player enter the pattern print('enter the pattern:' response input(''upper( if response !pattern print('incorrect!' print('the pattern was'pattern else print('correct!' for letter in pattern playsound playsound('soundletter wav' if response !patternsound mimic |
7,027 | print('you scored'len(pattern 'points 'print('thanks for playing!'break time sleep( exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you delete or comment out print('\ on line what happens if you change response !pattern on line to false project # |
7,028 | spongecase you've probably seen the "mocking spongebobmemea picture of spongebob squarepantswith caption whose text alternates between upperand lowercase letters to indicate sarcasmlike thisusing spongebob memes does not make you witty for some randomnessthe text sometimes doesn' alternate capitalization this short program uses the upper(and lower(string methods to convert your message into "spongecase the program is also set up so that other programs can import it as module with import spongecase and then call the spongecase englishtospongecase(function |
7,029 | when you run spongecase pythe output will look like thisspongecaseby al sweigart al@inventwithpython com enter your messageusing spongebob memes does not make you witty using spongebob memes does not make you witty (copied spongetext to clipboard how it works the code in this program uses for loop on line to iterate over every character in the message string the useupper variable contains boolean variable to indicate if the character should be made uppercase (if trueor lowercase (if falselines and toggle the boolean value in useupper (that isset it to its opposite valuein percent of the iterations this means that the casing almost always switches between upperand lowercase """spongecaseby al sweigart al@inventwithpython com translates english messages into spongetext view this code at tagstinybeginnerword"" import random try import pyperclip pyperclip copies text to the clipboard except importerror pass if pyperclip is not installeddo nothing it' no big deal def main() """run the spongetext program "" print('''spongecaseby al sweigart al@inventwithpython com enter your message:''' spongetext englishtospongecase(input('') print( print(spongetext try pyperclip copy(spongetext print('(copied spongetext to clipboard )' except pass do nothing if pyperclip wasn' installed def englishtospongecase(message) """return the spongetext form of the given string "" spongetext ' project # |
7,030 | useupper false for character in message if not character isalpha() spongetext +character continue if useupper spongetext +character upper( else spongetext +character lower( flip the case of the time if random randint( < useupper not useupper flip the case return spongetext if this program was run (instead of imported)run the game if __name__ ='__main__' main(exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change random randint( on line to random randint( ) what happens if you delete or comment out useupper not useupper on line spongecase |
7,031 | sudoku puz zle sudoku is popular puzzle game in newspapers and mobile apps the sudoku board is grid in which the player must place the digits to onceand only oncein each rowcolumnand subgrid the game begins with few spaces already filled in with digitscalled givens well-formed sudoku puzzle will have only one possible valid solution |
7,032 | when you run sudoku pythe output will look like thissudoku puzzleby al sweigart al@inventwithpython com --snip- ++ ++ enter moveor resetnewundooriginalor quit(for examplea move looks like " --snip-how it works objects of the sudokugrid class are the data structures that represent the sudoku grid you can call their methods to make modifications toor retrieve information aboutthe grid for examplethe makemove(method places number on the gridthe resetgrid(method restores the grid to its original stateand issolved(returns true if all the solution' numbers have been placed on the grid the main part of the programstarting on line uses sudokugrid object and its methods for this gamebut you could also copy and paste this class into other sudoku programs you create to reuse its functionality """sudoku puzzleby al sweigart al@inventwithpython com the classic number placement puzzle more info at view this code at tagslargegameobject-orientedpuzzle"" import copyrandomsys this game requires sudokupuzzle txt file that contains the puzzles download it from here' sample of the content in this file sudoku puzzle |
7,033 | empty_space grid_length box_length full_grid_size grid_length grid_length class sudokugrid def __init__(selforiginalsetup) originalsetup is string of characters for the puzzle setupwith numbers and periods (for the blank spaces see self originalsetup originalsetup the state of the sudoku grid is represented by dictionary with (xykeys and values of the number (as stringat that space self grid { self resetgrid(set the grid state to its original setup self moves [tracks each move for the undo feature def resetgrid(self) """reset the state of the gridtracked by self gridto the state in self originalsetup "" for in range( grid_length ) for in range( grid_length ) self grid[(xy)empty_space assert len(self originalsetup=full_grid_size goes from to goes from to while full_grid_size for in range(grid_length) self grid[(xy)self originalsetup[ + + def makemove(selfcolumnrownumber) """place the number at the column ( letter from to iand row (an integer from to on the grid "" 'abcdefghifind(columnconvert this to an integer int(row check if the move is being made on "givennumber if self originalsetup[ grid_length !empty_space return false self grid[(xy)number place this number on the grid we need to store separate copy of the dictionary object self moves append(copy copy(self grid) return true def undo(self) """set the current grid state to the previous state in the project # |
7,034 | self moves list ""if self moves =[]return no states in self movesso do nothing self moves pop(remove the current state if self moves =[]self resetgrid(elseset the grid to the last move self grid copy copy(self moves[- ]def display(self)"""display the current state of the grid on the screen ""print( 'display column labels for in range(grid_length)for in range(grid_length)if = display row labelprint(str( 'end=''print(self grid[(xy)'end=''if = or = display vertical lineprint(''end=''print(print newline if = or = display horizontal lineprint(++'def _iscompletesetofnumbers(selfnumbers)"""return true if numbers contains the digits through ""return sorted(numbers=list(' 'def issolved(self)"""returns true if the current grid is in solved state ""check each rowfor row in range(grid_length)rownumbers [for in range(grid_length)number self grid[(xrow)rownumbers append(numberif not self _iscompletesetofnumbers(rownumbers)return false check each columnfor column in range(grid_length)columnnumbers [for in range(grid_length)number self grid[(columny)columnnumbers append(numberif not self _iscompletesetofnumbers(columnnumbers)return false sudoku puzzle |
7,035 | check each box for boxx in ( ) for boxy in ( ) boxnumbers [ for in range(box_length) for in range(box_length) number self grid[(boxx xboxy ) boxnumbers append(number if not self _iscompletesetofnumbers(boxnumbers) return false return true print('''sudoku puzzleby al sweigart al@inventwithpython com sudoku is number placement logic puzzle game sudoku grid is grid of numbers try to place numbers in the grid such that every row columnand box has the numbers through once and only once for examplehere is starting sudoku grid and its solved form ++++ -- ++++ ''' input('press enter to begin ' load the sudokupuzzles txt file with open('sudokupuzzles txt'as puzzlefile puzzles puzzlefile readlines( remove the newlines at the end of each puzzle for ipuzzle in enumerate(puzzles) puzzles[ipuzzle strip( grid sudokugrid(random choice(puzzles) while truemain game loop grid display( check if the puzzle is solved if grid issolved() print('congratulationsyou solved the puzzle!' print('thanks for playing!' sys exit( project # |
7,036 | get the player' actionwhile truekeep asking until the player enters valid action print(print newline print('enter moveor resetnewundooriginalor quit:'print('(for examplea move looks like " )'action input(''upper(strip(if len(action and action[ in (' '' '' '' '' ')player entered valid action break if len(action split()= spacenumber action split(if len(space! continue columnrow space if column not in list('abcdefghi')print('there is no column'columncontinue if not row isdecimal(or not ( <int(row< )print('there is no row'rowcontinue if not ( <int(number< )print('select number from to not 'numbercontinue break player entered valid move print(print newline if action startswith(' ')reset the gridgrid resetgrid(continue if action startswith(' ')get new puzzlegrid sudokugrid(random choice(puzzles)continue if action startswith(' ')undo the last movegrid undo(continue if action startswith(' ')view the original numbersoriginalgrid sudokugrid(grid originalsetupprint('the original grid looked like this:'originalgrid display(input('press enter to continue 'if action startswith(' ')sudoku puzzle |
7,037 | quit the game print('thanks for playing!'sys exit(handle the move the player selected if grid makemove(columnrownumber=falseprint('you cannot overwrite the original grid\' numbers 'print('enter original to view the original grid 'input('press enter to continue 'exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what error happens if you delete or rename the sudokupuzzles txt file and run the program what happens if you change str( on line to str( ) what happens if you change if = or = on line to if = or = : project # |
7,038 | - this program demonstrates the use of the pyttsx third-party module any message you enter will be spoken out loud by your operating system' text-to-speech capabilities although computer-generated speech is an incredibly complex branch of computer sciencethe pyttsx module provides an easy interface for itmaking this small program suitable for beginners once you've learned how to use the moduleyou can add generated speech to your own programs more information about the pyttsx module can be found at pypi org/project/pyttsx |
7,039 | when you run texttospeechtalker pythe output will look like thistext to speech talkerby al sweigart al@inventwithpython com text-to-speech using the pyttsx modulewhich in turn uses the nsspeechsynthesizer (on macos)sapi (on windows)or espeak (on linuxspeech engines enter the text to speakor quit to quit hello my name is guido van robot quit thanks for playinghow it works this program is short because the pyttsx module handles all of the textto-speech code to use this moduleinstall it by following the instructions in this book' introduction once you've done soyour python script can import it with import pyttsx and call the pyttsc init(function this returns an engine object that represents the text-to-speech engine this object has say(method to which you can pass string of text for the computer to speak when you run the runandwait(method """text to speech talkerby al sweigart al@inventwithpython com an example program using the text-to-speech features of the pyttsx module view this code at tagstinybeginner"" import sys try import pyttsx except importerror print('the pyttsx module needs to be installed to run this' print('program on windowsopen command prompt and run:' print('pip install pyttsx ' print('on macos and linuxopen terminal and run:' print('pip install pyttsx ' sys exit( tts pyttsx init(initialize the tts engine print('text to speech talkerby al sweigart al@inventwithpython com' print('text-to-speech using the pyttsx modulewhich in turn uses' print('the nsspeechsynthesizer (on macos)sapi (on windows)or' print('espeak (on linuxspeech engines ' print( print('enter the text to speakor quit to quit ' while true text input('' project # |
7,040 | if text upper(='quit'print('thanks for playing!'sys exit(tts say(textadd some text for the tts engine to say tts runandwait(make the tts engine say it exploring the program this is base programso there aren' many options to customize it insteadconsider what other programs of yours would benefit from text-to-speech text-to-speech talker |
7,041 | three-card monte three-card monte is common scam played on gullible tourists and other easy marks three playing cardsone of which is the "red ladyqueen of heartsare put facedown on cardboard box the dealer quickly rearranges the cards and then asks the mark to pick the queen of hearts but the dealer can use all sorts of tricks to hide the card or otherwise cheatguaranteeing that the victim never wins it' also common for the dealer to have shills in the crowd who secretly work with the dealer but pretend to win the game (to make the victim think they too could winor purposefully lose badly (to make the victim think they could do much betterthis program shows the three cards and then quickly describes series of swaps at the endit clears the screenand the player must pick card |
7,042 | experienceyou can enable the cheat featurewhich causes the player to always loseeven if they select the correct card the program in action when you run threecardmonte pythe output will look like thisthree-card monteby al sweigart al@inventwithpython com find the red lady (the queen of hearts)keep an eye on how the cards move here are the cards___ ___ ___ | | | |__j|__q|__ press enter when you are ready to begin swapping left and middle swapping right and middle swapping middle and left swapping right and left swapping left and middle --snipwhich card has the queen of hearts(left middle rightmiddle ___ ___ ___ | | | |__q|__ |__jyou lostthanks for playingsuckerhow it works in this programwe use (ranksuittuple to represent playing card the rank is string representing the card numbersuch as ' '' '' 'or ' 'and the suit is string of either heartclubspadeor diamond emoji since you cannot enter the emoji character using your keyboardwe'll use the chr(function calls on lines to to produce them the tuple (' '''represents the nine of diamonds instead of printing these tuples directlythe displaycards(function on lines to interprets them and displays ascii-art representations on the screenlike in project "blackjack the cards argument for this function is list of the playing card tuplesallowing multiple cards to be displayed in row three-card monte |
7,043 | find the queen of hearts after cards have been swapped around (in the real-life versionthe scammer palms the queen of hearts so you always lose more info at view this code at tagslargecard gamegame"" import randomtime set up the constants num_swaps (!try changing this to or delay (!try changing this or the card suit characters hearts chr( character is ' diamonds chr( character is ' spades chr( character is ' clubs chr( character is ' list of chr(codes is at the indexes of -card list left middle right def displaycards(cards) """display the cards in "cards"which is list of (ranksuit tuples "" rows [''''''''''stores the text to display for icard in enumerate(cards) ranksuit card the card is tuple data structure rows[ +___ print the top line of the card rows[ +'|{format(rank ljust( ) rows[ +'{format(suit rows[ +'| {}format(rank rjust( ' ') print each row on the screen for in range( ) print(rows[ ] def getrandomcard() """returns random card that is not the queen of hearts "" while truemake cards until you get non-queen of hearts rank random choice(list(' jqka'[' '] suit random choice([heartsdiamondsspadesclubs] return the card as long as it' not the queen of hearts if rank !'qand suit !hearts return (ranksuit project # |
7,044 | print('three-card monteby al sweigart al@inventwithpython com' print( print('find the red lady (the queen of hearts)keep an eye on how' print('the cards move ' print( show the original arrangement cards [(' 'hearts)getrandomcard()getrandomcard() random shuffle(cardsput the queen of hearts in random place print('here are the cards:' displaycards(cards input('press enter when you are ready to begin ' print the swaps for in range(num_swaps) swap random choice([' - '' - '' - '' - '' - '' - '] if swap =' - ' print('swapping left and middle ' cards[left]cards[middlecards[middle]cards[left elif swap =' - ' print('swapping middle and right ' cards[middle]cards[rightcards[right]cards[middle elif swap =' - ' print('swapping left and right ' cards[left]cards[rightcards[right]cards[left elif swap =' - ' print('swapping middle and left ' cards[middle]cards[leftcards[left]cards[middle elif swap =' - ' print('swapping right and middle ' cards[right]cards[middlecards[middle]cards[right elif swap =' - ' print('swapping right and left ' cards[right]cards[leftcards[left]cards[right time sleep(delay print several new lines to hide the swaps print('\ ask the user to find the red lady while truekeep asking until leftmiddleor right is entered print('which card has the queen of hearts(left middle right)' guess input(''upper( get the index in cards for the position that the player entered if guess in ['left''middle''right'] if guess ='left' guessindex elif guess ='middle' guessindex elif guess ='right'three-card monte |
7,045 | guessindex break (!uncomment this code to make the player always lose #if cards[guessindex=(' 'hearts) player has wonso let' move the queen possiblenewindexes [ possiblenewindexes remove(guessindexremove the queen' index newind random choice(possiblenewindexeschoose new index place the queen at the new index cards[guessindex]cards[newindcards[newind]cards[guessindex displaycards(cardsshow all the cards check if the player won if cards[guessindex=(' 'hearts) print('you won!' print('thanks for playing!' else print('you lost!' print('thanks for playingsucker!'after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followinguse the backspace-printing technique from project "progress bar,to display each swap message briefly and then print \ characters to erase it before printing the next one create four-card monte game for added difficulty exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change [(' 'hearts)getrandomcard()getrandomcard()on line to [(' 'hearts)(' 'hearts)(' 'hearts)] what happens if you change list(' jqka'on line to list('abcdefghijk') what happens if you delete or comment out time sleep(delayon line project # |
7,046 | - - tic-tac-toe is classic pencil-and-paper game played on grid players take turns placing their or markstrying to get three in row most games of tic-tac-toe end in tiebut it is possible to outsmart your opponent if they're not careful |
7,047 | when you run tictactoe pythe output will look like thiswelcome to tic-tac-toe -+-+ -+-+ what is ' move( - -+-+ -+-+ what is ' move( - --snip- | | -+-+ | | -+-+ | | the game is tiethanks for playinghow it works to represent tic-tac-toe boards in this programwe use dictionary with keys ' through ' for the spaces on the board the numbered spaces are arranged in the same way as phone' keypad the values in this dictionary are the string 'xor 'ofor player' mark and for an empty space """tic-tac-toeby al sweigart al@inventwithpython com the classic board game view this code at tagsshortboard gamegametwo-player"" all_spaces [' '' '' '' '' '' '' '' '' ' xoblank ' '' 'constants for string values def main() print('welcome to tic-tac-toe!' gameboard getblankboard(create ttt board dictionary currentplayernextplayer xo goes firsto goes next while truemain game loop display the board on the screen print(getboardstr(gameboard) project # |
7,048 | keep asking the player until they enter number - move none while not isvalidspace(gameboardmove) print('what is {}\' move( - )format(currentplayer) move input('' updateboard(gameboardmovecurrentplayermake the move check if the game is over if iswinner(gameboardcurrentplayer)check for winner print(getboardstr(gameboard) print(currentplayer has won the game!' break elif isboardfull(gameboard)check for tie print(getboardstr(gameboard) print('the game is tie!' break switch turns to the next player currentplayernextplayer nextplayercurrentplayer print('thanks for playing!' def getblankboard() """create newblank tic-tac-toe board "" map of space numbers | | -+-+ | | -+-+ | | keys are through the values are xoor blank board { for space in all_spaces board[spaceblank all spaces start as blank return board def getboardstr(board) """return text-representation of the board "" return '' {}|{}|{ -+-+ {}|{}|{ -+-+ {}|{}|{ ''format(board[' ']board[' ']board[' '] board[' ']board[' ']board[' '] board[' ']board[' ']board[' '] def isvalidspace(boardspace) """returns true if the space on the board is valid space number and the space is blank "" return space in all_spaces and board[space=blank def iswinner(boardplayer) """return true if player is winner on this tttboard ""tic-tac-toe |
7,049 | shorter variable names used here for readability bp boardplayer check for marks across rows columnsand diagonals return (( [' '= [' '= [' '=por across top ( [' '= [' '= [' '=por across middle ( [' '= [' '= [' '=por across bottom ( [' '= [' '= [' '=por down left ( [' '= [' '= [' '=por down middle ( [' '= [' '= [' '=por down right ( [' '= [' '= [' '=por diagonal ( [' '= [' '= [' '= )diagonal def isboardfull(board) """return true if every space on the board has been taken "" for space in all_spaces if board[space=blank return false if any space is blankreturn false return true no spaces are blankso return true def updateboard(boardspacemark) """sets the space on the board to mark "" board[spacemark if __name__ ='__main__' main(call main(if this module is runbut not when imported exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change xoblank ' '' 'on line to xoblank ' '' '' what happens if you change board[spacemark on line to board[spacex what happens if you change board[spaceblank on line to board[spacex project # |
7,050 | tower of hanoi the tower of hanoi is stack-moving puzzle game that features three poles on which you can stack various-sized disks the object of the game is to move one tower of disks to another pole howeveronly one disk can be moved at timeand larger disks cannot be placed on top of smaller ones figuring out certain pattern will help you solve this puzzle can you discover it(hinttry setting the total_disks variable to or to solve an easier version first |
7,051 | when you run towerofhanoi pythe output will look like thisthe tower of hanoiby al sweigart al@inventwithpython com move the tower of disksone disk at timeto another tower larger disks cannot rest on top of smaller disk more info at |@ @@ @@@@ @@@@@@ @@@@@@@@ @@@@ |||||| |||||| enter the letters of "fromand "totowersor quit ( ab to moves disk from tower to tower ab ||||||@@ @||@@@ @@||@@@@ @@@||@@@@@ @@@@@ | enter the letters of "fromand "totowersor quit ( ab to moves disk from tower to tower --snip-how it works the data structure that represents tower is list of integers each integer is the size of the disk the first integer in the list represents the bottom diskand the last integer represents the top disk for example[ would represent the following tower||@@ @@@@@ @@@@@@@@ @@@@python' append(and pop(list methods can add and remove values from the end of the listrespectively just as somelist[ and somelist[ allow us to access the first and second values in listpython lets us use negative indexes to access values from the end of the list using expressions project # |
7,052 | values in listrespectively this is useful for finding the disk currently at the top of the tower """the tower of hanoiby al sweigart al@inventwithpython com stack-moving puzzle game view this code at tagsshortgamepuzzle"" import copy import sys total_disks more disks means more difficult puzzle start with all disks on tower complete_tower list(range(total_disks - ) def main() print("""the tower of hanoiby al sweigart al@inventwithpython com move the tower of disksone disk at timeto another tower larger disks cannot rest on top of smaller disk more info at "" set up the towers the end of the list is the top of the tower towers {' 'copy copy(complete_tower)' '[]' '[] while truerun single turn display the towers and disks displaytowers(towers ask the user for move fromtowertotower askforplayermove(towers move the top disk from fromtower to totower disk towers[fromtowerpop( towers[totowerappend(disk check if the user has solved the puzzle if complete_tower in (towers[' ']towers[' ']) displaytowers(towersdisplay the towers one last time print('you have solved the puzzlewell done!' sys exit( def askforplayermove(towers) """asks the player for move returns (fromtowertotower"" while truekeep asking player until they enter valid move print('enter the letters of "fromand "totowersor quit 'tower of hanoi |
7,053 | print('( ab to moves disk from tower to tower )' response input(''upper(strip( if response ='quit' print('thanks for playing!' sys exit( make sure the user entered valid tower letters if response not in ('ab''ac''ba''bc''ca''cb') print('enter one of abacbabccaor cb ' continue ask player again for their move syntactic sugar use more descriptive variable names fromtowertotower response[ ]response[ if len(towers[fromtower]= the "fromtower cannot be an empty tower print('you selected tower with no disks ' continue ask player again for their move elif len(towers[totower]= any disk can be moved onto an empty "totower return fromtowertotower elif towers[totower][- towers[fromtower][- ] print('can\' put larger disks on top of smaller ones ' continue ask player again for their move else this is valid moveso return the selected towers return fromtowertotower def displaytowers(towers) """display the current state "" display the three towers for level in range(total_disks- - ) for tower in (towers[' ']towers[' ']towers[' ']) if level >len(tower) displaydisk( display the bare pole with no disk else displaydisk(tower[level]display the disk print( display the tower labels aband emptyspace (total_disks print('{ { }{ { }{ \nformat(emptyspace) def displaydisk(width) """display disk of the given width width of means no disk "" emptyspace (total_disks width if width = display pole segment without disk print(emptyspace '||emptyspaceend='' else project # |
7,054 | display the disk disk '@width numlabel str(widthrjust( ' ' print(emptyspace disk numlabel disk emptyspaceend='' if the program is run (instead of imported)run the game if __name__ ='__main__' main(exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you delete or comment out lines and what happens if you change emptyspace (total_disks widthon line to emptyspace ' what happens if you change width = on line to width ! tower of hanoi |
7,055 | trick questions what does yellow stone thrown into blue pond becomedo they have th of july in englandhow can doctor go days without sleepwhatever you think the answers to these trick questions areyou're probably wrong the questions in this program have been specifically crafted so that their answers are simpleobviousand misleading finding the true answer will require some cleverness copying the code from this book will spoil the funsince you'll see the answersso you might want to download and play this game from inventwithpython com/trickquestions py before looking at the source code |
7,056 | when you run trickquestions pythe output will look like thistrick questionsby al sweigart al@inventwithpython com can you figure out the answers to these trick questions(enter quit to quit at any time press enter to begin --snip-question score questiona year old person was born on the nd of february what year is their birthdayanswer incorrectthe answer istheir birthday is on february nd of every year press enter for the next question --snip-question score questionif there are ten apples and you take away twohow many do you haveanswereight incorrectthe answer istwo press enter for the next question --snip-how it works the questions variable holds list of dictionaries each dictionary represents single trick question and has the keys 'question''answer'and 'acceptthe values for 'questionand 'answerare strings the program displays when it poses the question to the player and reveals the answerrespectively the value for the 'acceptkey is list of strings if the player enters response that contains any of these stringsit' accepted as correct this allows the player to enter free-form text as their reply the program is reasonably accurate in detecting when they've provided the correct answer """trick questionsby al sweigart al@inventwithpython com quiz of several trick questions view this code at tagslargehumor"" import randomsys questions is list of dictionarieseach dictionary represents trick question and its answer the dictionary has the keys 'question (which holds the text of the question)'answer(which holds the text of the answer)and 'accept(which holds list of strings thatif the player' answer contains any ofthey've answered correctly (!try coming up with your own trick questions to add here questions trick questions |
7,057 | {'question'"how many times can you take apples from pile of apples?"'answer'"once then you have pile of apples "'accept'['once''one'' ']}{'question''what begins with "eand ends with "ebut only has one letter in it?''answer'"an envelope "'accept'['envelope']}{'question'"is it possible to draw square with three sides?"'answer'"yes all squares have three sides they also have fourth side "'accept'['yes']}{'question'"how many times can piece of paper be folded in half by hand without unfolding?"'answer'"once then you are folding it in quarters "'accept'['one'' ''once']}{'question'"what does towel get as it dries?"'answer'"wet "'accept'['wet']}{'question'"what does towel get as it dries?"'answer'"drier "'accept'['drier''dry']}{'question'"imagine you are in haunted house full of evil ghosts what do you have to do to stay safe?"'answer'"nothing you're only imagining it "'accept'['nothing''stop']}{'question'" taxi driver is going the wrong way down one-way street she passes ten cops but doesn' get ticket why not?"'answer'"she was walking "'accept'['walk']}{'question'"what does yellow stone thrown into blue pond become?"'answer'"wet "'accept'['wet']}{'question'"how many miles does must cyclist bike to get to training?"'answer'"none they're training as soon as they get on the bike "'accept'['none''zero'' ']}{'question'"what building do people want to leave as soon as they enter?"'answer'"an airport "'accept'['airport''bus''port''train''station''stop']}{'question'"if you're in the middle of square house facing the west side with the south side to your left and the north side to your rightwhich side of the house are you next to?"'answer'"none you're in the middle "'accept'['none''middle''not''any']}{'question'"how much dirt is in hole meters wide meters longand meters deep?"'answer'"there is no dirt in hole "'accept'['no''none''zero']}{'question'" girl mails letter from america to japan how many miles did the stamp move?"'answer'"zero the stamp was in the same place on the envelope the whole time "'accept'['zero'' ''none''no']}{'question'"what was the highest mountain on earth the day before mount everest was discovered?"'answer'"mount everest was still the highest mountain of earth the day before it was discovered "'accept'['everest']}{'question'"how many fingers do most people have on their two hands?"project # |
7,058 | 'answer'"eight they also have two thumbs "'accept'['eight'' ']}{'question'"the th of july is holiday in america do they have th of july in england?"'answer'"yes all countries have th of july on their calendar "'accept'['yes']}{'question'"which letter of the alphabet makes honey?"'answer'"none bee is an insectnot letter "'accept'['no''none''not']}{'question'"how can doctor go days without sleep?"'answer'"by sleeping at night "'accept'['night''evening']}{'question'"how many months have days?"'answer'" all months have days some have more days as well "'accept'[' ''twelve''all']}{'question'"how many two cent stamps are in dozen?"'answer'" dozen "'accept'[' ''twelve''dozen']}{'question'"why is it illegal for person living in north dakota to be buried in south dakota?"'answer'"because it is illegal to bury someone alive "'accept'['alive''living''live']}{'question'"how many heads does two-headed coin have?"'answer'"zero coins are just circular pieces of metal they don' have heads "'accept'['zero''none''no'' ']}{'question'"what kind of vehicle has four wheels and flies?"'answer'" garbage truck "'accept'['garbage''dump''trash']}{'question'"what kind of vehicle has four wheels and flies?"'answer'"an airplane "'accept'['airplane''plane']}{'question'"what five-letter word becomes shorter by adding two letters?"'answer'"short "'accept'['short']}{'question'"gwen' mother has five daughters four are named hahahehehihiand hoho what' the fifth daughter' name?"'answer'"gwen "'accept'['gwen']}{'question'"how long is fence if there are three fence posts each one meter apart?"'answer'"two meters long "'accept'[' ''two']}{'question'"how many legs does dog have if you count its tail as leg?"'answer'"four calling tail leg doesn' make it one "'accept'['four'' ']}{'question'"how much more are pennies worth compared to pennies?"'answer'"one cent "'accept'[' ''one']}{'question'"what two things can you never eat for breakfast?"'answer'"lunch and dinner "'accept'['lunch''dinner''supper']}{'question'"how many birthdays does the average person have?"'answer'"one you're only born once "'accept'['one'' ''once'born']}{'question'"where was the united states declaration of independence signed?"'answer'"it was signed at the bottom "trick questions |
7,059 | 'accept'['bottom']}{'question'" person puts two walnuts in their pocket but only has one thing in their pocket five minutes later what is it?"'answer'" hole "'accept'['hole']}{'question'"what did the sculptor make that no one could see?"'answer'"noise "'accept'['noise']}{'question'"if you drop raw egg on concrete floorwill it crack?"'answer'"no concrete is very hard to crack "'accept'['no']}{'question'"if it takes ten people ten hours to build fencehow many hours does it take five people to build it?"'answer'"zero it' already built "'accept'['zero''no'' ''already''built']}{'question'"which is heavier pounds of rocks or pounds of feathers?"'answer'"neither they weigh the same "'accept'['neither''none''no''same''even''balance']}{'question'"what do you have to do to survive being bitten by poisonous snake?"'answer'"nothing only venomous snakes are deadly "'accept'['nothing''anything']}{'question'"what three consecutive days don' include sundaywednesdayor friday?"'answer'"yesterdaytodayand tomorrow "'accept'['yesterday''today''tomorrow']}{'question'"if there are ten apples and you take away twohow many do you have?"'answer'"two "'accept'[' ''two']}{'question'" year old person was born on the nd of february what year is their birthday?"'answer'"their birthday is on february nd of every year "'accept'['every''each']}{'question'"how far can you walk in the woods?"'answer'"halfway then you are walking out of the woods "'accept'['half'' / ']}{'question'"can man marry his widow' sister?"'answer'"nobecause he' dead "'accept'['no']}{'question'"what do you get if you divide one hundred by half?"'answer'"one hundred divided by half is two hundred one hundred divided by two is fifty "'accept'['two'' ']}{'question'"what do you call someone who always knows where their spouse is?"'answer'" widow or widower "'accept'['widow''widower']}{'question'"how can someone take photo but not be photographer?"'answer'"they can be thief "'accept'['thief''steal''take''literal']}{'question'"an electric train leaves the windy city of chicago at pm on monday heading south at kilometers per hour which way does the smoke blow from the smokestack?"'answer'"electric trains don' have smokestacks "'accept'["don' ""doesn' "'not''no''none']}{'question''what is the only word that rhymes with "orange"?''answer'"orange " project # |
7,060 | 'accept'['orange']}{'question'"who is the president if the vice president dies?"'answer'"the current president "'accept'['president''current''already']}{'question'" doctor gives you three pills with instructions to take one every half-hour how long will the pills last?"'answer'"one hour "'accept'[' ''one']}{'question'"where is there an ocean with no water?"'answer'"on map "'accept'['map']}{'question'"what is the size of rhino but weighs nothing?"'answer'" rhino' shadow "'accept'['shadow']}{'question'"the clerk at butcher shop is exactly centimeters tall what do they weigh?"'answer'"the clerk weighs meat "'accept'['meat']} correct_text ['correct!''that is right '"you're right " 'you got it ''righto!' incorrect_text ['incorrect!'"nopethat isn' it "'nope ' 'not quite ''you missed it ' print('''trick questionsby al sweigart al@inventwithpython com can you figure out the answers to these trick questions (enter quit to quit at any time ''' input('press enter to begin ' random shuffle(questions score for questionnumberqa in enumerate(questions)main program loop print('\ "clearthe screen print('question:'questionnumber print('score:'score'/'len(questions) print('question:'qa['question'] response input(answer'lower( if response ='quit' print('thanks for playing!' sys exit( correct false for acceptanceword in qa['accept'] if acceptanceword in response correct true if correct text random choice(correct_text print(textqa['answer'] score + trick questions |
7,061 | else text random choice(incorrect_text print(text'the answer is:'qa['answer'] response input('press enter for the next question 'lower( if response ='quit' print('thanks for playing!' sys exit( print("that' all the questions thanks for playing!"after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make exploring the program this is base programso there aren' many options to customize it insteadconsider other uses for question-and-answer program format project # |
7,062 | ye gabriele cirullia web developerinvented the game in one weekend it was inspired by veewo studios gamewhich in turn was inspired by threes! game by the development team sirvo in you must merge numbers on board to clear them from the screen two merge into two merge into an and so on the game adds new to the board on each merging the objective is to reach before the entire board fills up |
7,063 | when you run twentyfortyeight pythe output will look like thistwenty forty-eightby al sweigart al@inventwithpython com --snip-++++ ++++ ++++ ++++ ++++score enter move(wasd or to quit--snip-how it works this program implements its sliding behavior using "columndata structuresrepresented by lists of four stringsblank ( single-space string)' '' '' 'and so on the first value in this list represents the bottom of the columnwhile the last represents the top numbers that combine in column always slide downwardwhether the player slides the tiles updownleftor right think of it as gravity pulling the tiles in these directions for examplefigure - shows board with tiles sliding to the right we'll create four lists to represent the columns[' '' '' ''['''' '['''' '[''''the combinetilesincolumn(function accepts one column list and returns anotherwith the matching numbers combined and shifted toward the bottom the code that calls combinetilesincolumn(handles creating the column lists in the appropriate direction and updating the game board with the returned list project # |
7,064 | figure - columns (highlightedwhen game board is sliding to the right """twenty forty-eightby al sweigart al@inventwithpython com sliding tile game to combine exponentially-increasing numbers inspired by gabriele cirulli' which is clone of veewo studios which in turn is clone of the threesgame more info at view this code at tagslargegamepuzzle"" import randomsys set up the constants blank ' value that represents blank space on the board def main() print('''twenty forty-eightby al sweigart al@inventwithpython com slide all the tiles on the board in one of four directions tiles with like numbers will combine into larger-numbered tiles new tile is added to the board on each move you win if you can create tile you lose if the board fills up the tiles before then ''' input('press enter to begin ' gameboard getnewboard( while truemain game loop drawboard(gameboard print('score:'getscore(gameboard) playermove askforplayermove( gameboard makemove(gameboardplayermove addtwotoboard(gameboard twenty forty-eight |
7,065 | if isfull(gameboard) drawboard(gameboard print('game over thanks for playing!' sys exit( def getnewboard() """returns new data structure that represents board it' dictionary with keys of (xytuples and values of the tile at that space the tile is either power-of-two integer or blank the coordinates are laid out as +-+-+-+- +-+-+-+- +-+-+-+- +-+-+-+- +-+-+-+-+"" newboard {contains the board data structure to be returned loop over every possible space and set all the tiles to blank for in range( ) for in range( ) newboard[(xy)blank pick two random spaces for the two starting startingtwosplaced the number of starting spaces picked while startingtwosplaced repeat for duplicate spaces randomspace (random randint( )random randint( ) make sure the randomly selected space isn' already taken if newboard[randomspace=blank newboard[randomspace startingtwosplaced startingtwosplaced return newboard def drawboard(board) """draws the board data structure on the screen "" go through each possible space left to righttop to bottomand create list of what each space' label should be labels [ list of strings for the number/blank for that tile for in range( ) for in range( ) tile board[(xy)get the tile at this space make sure the label is spaces long labelforthistile str(tilecenter( labels append(labelforthistile the {are replaced with the label for that tile project # |
7,066 | print("" ++++ |{}|{}|{}|{} ++++ |{}|{}|{}|{} ++++ |{}|{}|{}|{} ++++ |{}|{}|{}|{} ++++ ""format(*labels) def getscore(board) """returns the sum of all the tiles on the board data structure "" score loop over every space and add the tile to the score for in range( ) for in range( ) only add non-blank tiles to the score if board[(xy)!blank score score board[(xy) return score def combinetilesincolumn(column) """the column is list of four tile index is the "bottomof the columnand tiles are pulled "downand combine if they are the same for examplecombinetilesincolumn([ blank blank] returns [ blankblankblank"" copy only the numbers (not blanksfrom column to combinedtiles combinedtiles [ list of the non-blank tiles in column for in range( ) if column[ !blank combinedtiles append(column[ ] keep adding blanks until there are tiles while len(combinedtiles combinedtiles append(blank combine numbers if the one "aboveit is the sameand double it for in range( )skip index it' the topmost space if combinedtiles[ =combinedtiles[ ] combinedtiles[ * double the number in the tile move the tiles above it down one space for aboveindex in range( )twenty forty-eight |
7,067 | combinedtiles[aboveindexcombinedtiles[aboveindex combinedtiles[ blank topmost space is always blank return combinedtiles def makemove(boardmove) """carries out the move on the board the move argument is either ' '' '' 'or 'dand the function returns the resulting board data structure "" the board is split up into four columnswhich are different depending on the direction of the move if move =' ' allcolumnsspaces [[( )( )( )( )] [( )( )( )( )] [( )( )( )( )] [( )( )( )( )] elif move =' ' allcolumnsspaces [[( )( )( )( )] [( )( )( )( )] [( )( )( )( )] [( )( )( )( )] elif move =' ' allcolumnsspaces [[( )( )( )( )] [( )( )( )( )] [( )( )( )( )] [( )( )( )( )] elif move =' ' allcolumnsspaces [[( )( )( )( )] [( )( )( )( )] [( )( )( )( )] [( )( )( )( )] the board data structure after making the move boardaftermove { for columnspaces in allcolumnsspacesloop over all columns get the tiles of this column (the first tile is the "bottom of the column) firsttilespace columnspaces[ secondtilespace columnspaces[ thirdtilespace columnspaces[ fourthtilespace columnspaces[ firsttile board[firsttilespace secondtile board[secondtilespace thirdtile board[thirdtilespace fourthtile board[fourthtilespace form the column and combine the tiles in it column [firsttilesecondtilethirdtilefourthtile combinedtilescolumn combinetilesincolumn(column set up the new board data structure with the combined tiles boardaftermove[firsttilespacecombinedtilescolumn[ project # |
7,068 | boardaftermove[secondtilespacecombinedtilescolumn[ boardaftermove[thirdtilespacecombinedtilescolumn[ boardaftermove[fourthtilespacecombinedtilescolumn[ return boardaftermove def askforplayermove() """asks the player for the direction of their next move (or quit ensures they enter valid moveeither ' '' ''sor ' "" print('enter move(wasd or to quit)' while truekeep looping until they enter valid move move input(''upper( if move =' ' end the program print('thanks for playing!' sys exit( either return the valid moveor loop back and ask again if move in (' '' '' '' ') return move else print('enter one of " "" "" "" "or " ' def addtwotoboard(board) """adds new tile randomly to the board "" while true randomspace (random randint( )random randint( ) if board[randomspace=blank board[randomspace return return after finding one non-blank tile def isfull(board) """returns true if the board data structure has no blanks "" loop over every space on the board for in range( ) for in range( ) if space is blankreturn false if board[(xy)=blank return false return true no space is blankso return true if this program was run (instead of imported)run the game if __name__ ='__main__' try main( except keyboardinterrupt sys exit(when ctrl- is pressedend the program twenty forty-eight |
7,069 | try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change return score on line to return what happens if you change board[randomspace on line to board[randomspace project # |
7,070 | vigenere cipher the vigenere ciphermisattributed to thcentury cryptographer blaise de vigenere (others had independently invented it earlier)was impossible to crack for hundreds of years it is essentially the caesar cipherexcept it makes use of multipart key the so-called vigenere key is wordor even random series of letters each letter represents number by which to shift the letter in the messagea represents shifting letter in the message by represents represents and so on for exampleif vigenere key is the word "cat,the represents shift of the represents and the represents the first letter of the message gets shifted by the second letter by and the third letter by for the fourth letterwe repeat the key of this use of multiple caesar cipher keys is what gives the vigenere cipher its strength the possible number of combinations is too big to brute force |
7,071 | analysis weakness that can crack the simple substitution cipher for centuriesthe vigenere cipher represented the state of the art in cryptography you'll notice many similarities between the code for the vigenere and caesar cipher programs more info about the vigenere cipher can be found at more about ciphers and code breakingyou can read my book cracking codes with python (no starch press the program in action when you run vigenere pythe output will look like thisvigenere cipherby al sweigart al@inventwithpython com the vigenere cipher is polyalphabetic substitution cipher that was powerful enough to remain unbroken for centuries do you want to ( )ncrypt or ( )ecrypte please specify the key to use it can be word or any combination of letterspizza enter the message to encrypt meet me by the rose bushes tonight encrypted messagebmds mt jx sht znre qcrgeh bnmivps full encrypted text copied to clipboard how it works because the encryption and decryption processes are fairly similarthe translatemessage(function handles both of them the encryptmessage(and decryptmessage(functions are merely wrapper functions for translatemessage(in other wordsthey are functions that adjust their argumentsforward these to another functionand then return that function' return value this program uses these wrapper functions so that they can be called in manner similar to encryptmessage(and decryptmessage(in project "simple substitution cipher you can import these projects as modules in other programs to make use of their encryption code without having to copy and paste the code directly into your new program """vigenere cipherby al sweigart al@inventwithpython com the vigenere cipher is polyalphabetic substitution cipher that was powerful enough to remain unbroken for centuries more info at view this code at tagsshortcryptographymath"" try import pyperclip pyperclip copies text to the clipboard project # |
7,072 | pass if pyperclip is not installeddo nothing it' no big deal every possible symbol that can be encrypted/decrypted letters 'abcdefghijklmnopqrstuvwxyz def main() print('''vigenere cipherby al sweigart al@inventwithpython com the vigenere cipher is polyalphabetic substitution cipher that was powerful enough to remain unbroken for centuries ''' let the user specify if they are encrypting or decrypting while truekeep asking until the user enters or print('do you want to ( )ncrypt or ( )ecrypt?' response input(''lower( if response startswith(' ') mymode 'encrypt break elif response startswith(' ') mymode 'decrypt break print('please enter the letter or ' let the user specify the key to use while truekeep asking until the user enters valid key print('please specify the key to use ' print('it can be word or any combination of letters:' response input(''upper( if response isalpha() mykey response break let the user specify the message to encrypt/decrypt print('enter the message to {format(mymode) mymessage input('' perform the encryption/decryption if mymode ='encrypt' translated encryptmessage(mymessagemykey elif mymode ='decrypt' translated decryptmessage(mymessagemykey print('%sed message:(mymode title()) print(translated try pyperclip copy(translated print('full %sed text copied to clipboard (mymode) except pass do nothing if pyperclip wasn' installed def encryptmessage(messagekey)vigenere cipher |
7,073 | """encrypt the message using the key "" return translatemessage(messagekey'encrypt' def decryptmessage(messagekey) """decrypt the message using the key "" return translatemessage(messagekey'decrypt' def translatemessage(messagekeymode) """encrypt or decrypt the message using the key "" translated [stores the encrypted/decrypted message string keyindex key key upper( for symbol in messageloop through each character in message num letters find(symbol upper() if num !- - means symbol upper(was not in letters if mode ='encrypt' add if encrypting num +letters find(key[keyindex] elif mode ='decrypt' subtract if decrypting num -letters find(key[keyindex] num %len(lettershandle the potential wrap-around add the encrypted/decrypted symbol to translated if symbol isupper() translated append(letters[num] elif symbol islower() translated append(letters[numlower() keyindex + move to the next letter in the key if keyindex =len(key) keyindex else just add the symbol without encrypting/decrypting translated append(symbol return 'join(translated if this program was run (instead of imported)run the program if __name__ ='__main__' main( project # |
7,074 | try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens when you encrypt with the key ' ' what error do you cause when you delete or comment out mykey response on line vigenere cipher |
7,075 | wat in this solitaire puzzle gameyou must use three buckets (three-literfive-literand eight-liter bucketsto collect exactly four liters of water in one of the buckets buckets can only be emptiedcompletely filledor poured into another bucket for exampleyou can fill the five-liter bucket and then pour its contents into the three-liter bucketleaving you with full three-liter bucket and two liters of water in the five-liter bucket with some effortyou should be able to solve the puzzle but can you figure out how to solve it with the minimal number of moves |
7,076 | when you run waterbucket pythe output will look like thiswater bucket puzzleby al sweigart al@inventwithpython com try to get of water into one of these buckets + + + you can( )ill the bucket ( )mpty the bucket ( )our one bucket into another ( )uit select bucket or quit try to get of water into one of these buckets + --snip- |wwwwww |wwwwww |wwwwww |wwwwww |wwwwww+ + how it works the waterinbucket variable stores dictionary that represents the state of the water buckets the keys to this dictionary are the strings ' '' 'and ' (representing the buckets)and their values are integers (representing the liters of water in that bucketlines to use this dictionary to render the buckets and water on the screen the waterdisplay list contains either 'wwwwww(representing wateror (representing airand is passed to the format(string water bucket puzzle |
7,077 | bucketthe next five strings the five-liter bucketand the final three strings the three-liter bucket """water bucket puzzleby al sweigart al@inventwithpython com water pouring puzzle more info view this code at tagslargegamemathpuzzle"" import sys print('water bucket puzzleby al sweigart al@inventwithpython com' goal the exact amount of water to have in bucket to win steps keep track of how many steps the player made to solve this the amount of water in each bucket waterinbucket {' ' ' ' ' ' while truemain game loop display the current state of the buckets print( print('try to get str(goal' of water into one of these' print('buckets:' waterdisplay [contains strings for water or empty space get the strings for the bucket for in range( ) if waterinbucket[' ' waterdisplay append('add empty space else waterdisplay append('wwwwww'add water get the strings for the bucket for in range( ) if waterinbucket[' ' waterdisplay append('add empty space else waterdisplay append('wwwwww'add water get the strings for the bucket for in range( ) if waterinbucket[' ' waterdisplay append('add empty space else waterdisplay append('wwwwww'add water display the buckets with the amount of water in each one print('' |{ } |{ } project # |
7,078 | |{ } |{ } |{ } |{ } |{ } |{ } |{ } |{ } |{ } |{ } |{ } |{ } |{ } +++ ''format(*waterdisplay) check if any of the buckets has the goal amount of water for wateramount in waterinbucket values() if wateramount =goal print('good jobyou solved it in'steps'steps!' sys exit( let the player select an action to do with bucket print('you can:' print(( )ill the bucket' print(( )mpty the bucket' print(( )our one bucket into another' print(( )uit' while truekeep asking until the player enters valid action move input(''upper( if move ='quitor move =' ' print('thanks for playing!' sys exit( if move in (' '' '' ') break player has selected valid action print('enter fepor ' let the player select bucket while truekeep asking until valid bucket entered print('select bucket or quit:' srcbucket input(''upper( if srcbucket ='quit' print('thanks for playing!' sys exit( if srcbucket in (' '' '' ') break player has selected valid bucket carry out the selected action if move =' ' set the amount of water to the max size srcbucketsize int(srcbucket waterinbucket[srcbucketsrcbucketsize steps + elif move =' ' waterinbucket[srcbucket set water amount to nothing steps + water bucket puzzle |
7,079 | elif move =' 'let the player select bucket to pour intowhile truekeep asking until valid bucket entered print('select bucket to pour into or 'dstbucket input(''upper(if dstbucket in (' '' '' ')break player has selected valid bucket figure out the amount to pourdstbucketsize int(dstbucketemptyspaceindstbucket dstbucketsize waterinbucket[dstbucketwaterinsrcbucket waterinbucket[srcbucketamounttopour min(emptyspaceindstbucketwaterinsrcbucketpour out water from this bucketwaterinbucket[srcbucket-amounttopour put the poured out water into the other bucketwaterinbucket[dstbucket+amounttopour steps + elif move =' 'pass if the player selected canceldo nothing after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingadd variety by making the game configurable so you can specify any sizes for the three buckets and any amount for the goal quantity add "hintthat examines the amount of water in each bucket and provides the next step to take if the program can' figure out which action to take nextit can simply display " don' know what you should do next maybe start over?exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change waterinbucket[srcbucket on line to waterinbucket[srcbucket what happens if you change {' ' ' ' ' ' on line to {' ' ' ' ' ' } what happens if you change {' ' ' ' ' ' on line to {' ' ' ' ' ' } project # |
7,080 | tag the projects in this book are marked with set of tags that describe the type of program they are the first tag indicates their sizetiny ( to lines)short ( to lines)large ( to lines)and extra-large ( lines or morethe size tags are as followstiny# bitmap message# caesar hacker# collatz sequence# countdown# deep cave# diamonds# digital clock# digital stream# factor finder# fast draw# guess the number# gullible# hex grid# leetspeak# magic fortune ball# million dice roll statistics simulator# multiplication table# ninety-nine bottles# numeral systems counter# prime numbers# progress bar# rainbow# rock paper scissors (always-win version)# rot cipher# shining carpet# sine message# spongecase# text-tospeech talker |
7,081 | caesar cipher# calendar maker# cho-han# conway' game of life# dice roller# dna visualization# fibonacci# forest fire sim# ninety nniine boottels# periodic table of the elements# pig latin# powerball lottery# rock paper scissors# seven-segment display module# simple substitution cipher# snail race# sound mimic# tic-tac-toe# tower of hanoi# vigenere cipher large# blackjack# carrot in box# clickbait headline generator# dice math# ducklings# etching drawer# flooder# four in row# hacking minigame# hangman and guillotine# hourglass# hungry robots# langton' ant# lucky stars# mancala# maze runner # mondrian art generator# monty hall problem# rotating cube# royal game of ur# sliding tile puzzle# soroban japanese abacus# sudoku puzzle# three-card monte# trick questions# twenty forty-eight# water bucket puzzle extra-large# fish tank# 'accuse!# maze runner the remaining tags indicate the features of the programartistic# bitmap message# bouncing dvd logo# conway' game of life# countdown# deep cave# diamonds# dice math# digital clock# digital stream# dna visualization# ducklings# etching drawer# fish tank# hacking minigame# hex grid# hourglass# langton' ant# maze runner # mondrian art generator# rainbow# rotating cube# shining carpet# sine message# snail race# soroban japanese abacus beginner# bitmap message# caesar cipher# caesar hacker# carrot in box# cho-han# clickbait headline generator# collatz sequence# deep cave# diamonds# digital stream# factor finder# fast draw# guess the number# gullible# hex grid# leetspeak# magic fortune ball# million dice roll statistics simulator# multiplication table# ninety-nine bottles# rainbow# shining carpet# snail race# sound mimic# spongecase# text-to-speech talker bext# bouncing dvd logo# fish tank# flooder# forest fire sim# hourglass# langton' ant# mondrian art generator# rainbow board game# four in row# mancala# royal game of ur# tic-tac-toe card game# blackjack# three-card monte cryptography# caesar cipher# caesar hacker# rot cipher# simple substitution cipher# vigenere cipher appendix |
7,082 | dice math# fast draw# flooder# four in row# guess the number# hacking minigame# hangman and guillotine# hungry robots# 'accuse!# lucky stars# mancala# maze runner # maze runner # monty hall problem# rock paper scissors# rock paper scissors (always-win version)# royal game of ur# sliding tile puzzle# snail race# sound mimic# sudoku puzzle# three-card monte# tic-tactoe# tower of hanoi puzzle# twenty forty-eight# water bucket puzzle humor# clickbait headline generator# gullible# 'accuse!# magic fortune ball# powerball lottery# rock paper scissors (always-win version)# trick questions math# birthday paradox# caesar cipher# caesar hacker# collatz sequence# dice math# factor finder# fibonacci# million dice roll statistics simulator# monty hall problem# multiplication table# numeral systems counter# prime numbers# rotating cube# simple substitution cipher# soroban japanese abacus# vigenere cipher# water bucket puzzle maze# maze runner # maze runner module# progress bar# seven-segment display module multiplayer# lucky stars# snail race object-oriented# ducklings# sudoku puzzle puzzle# bagels# hacking minigame# hangman and guillotine# 'accuse!# sliding tile puzzle# sudoku puzzle# tower of hanoi puzzle# twenty forty-eight# water bucket puzzle science# dna visualization# periodic table of the elements scrolling# deep cave# digital stream# dna visualization# ducklings# ninety-nine bottles# ninety nniine boottels# prime numbers# rainbow simulation# birthday paradox# conway' game of life# dice roller# forest fire sim# hourglass# langton' ant# million dice roll statistics simulator# monty hall problem# powerball lottery# soroban japanese abacus two-player# carrot in box# four in row# mancala# royal game of ur# tic-tac-toe word# clickbait headline generator# hangman and guillotine# leetspeak# ninety nniine boottels# pig latin# spongecase tag index |
7,083 | char ac ter map the print(function allows you to easily make any character you can type on the keyboard appear on the screen howeverthere are many other characters you may like to displaythe heartsdiamondsclubsand spades card suitslinesshaded boxesarrowsmusic notesand so on you can obtain string values of these characters by passing their numeric codecalled unicode code pointto the chr(function text is stored on computers as series of numberswith each character represented by different number this appendix contains list of such code points |
7,084 | python' built-in chr(function accepts an integer argument and returns string of the number' character the ord(function does the oppositeit accepts string argument of single character and returns the character' number this number is the code point for the character in the unicode standard for exampleenter the following into the interactive shellchr( 'aord(' ' chr( 'bchr( 'not all numbers are valid code points for printable characters the terminal windows that show the text output of programs may be limited in which characters they can display the font the terminal window uses also must support the character your program prints the terminal window prints unicode replacement characterfor any character it is unable to print windowsterminal window has far more limited range of characters it can display this set is known as the windows glyph list and it appears in this appendix and on wikipedia at windows_glyph_list_ the code points for characters are often listed with base- hexadecimal numberas opposed to the base- decimal numbers we are used to instead of the decimal digits to hexadecimal has the digits to and then continues with the letters to hexadecimal numbers are often written with prefix to denote that the number that follows is in hex you can convert decimal integer value to string of the hexadecimal number with the hex(function you can convert string of the hexadecimal number to decimal integer with the int(functionpassing as the second argument for exampleenter the following into the interactive shellhex( ' hex( ' xahex( ' xfhex( ' hex( ' int(' ' character map |
7,085 | when calling the chr(functionyou must pass decimal integer as the argumentnot hexadecimal string table of code points the following are all the unicode code points in the set known as windows glyph list which are the characters supported by the windows terminal programcommand prompt both macos and linux can display more characters than are in this listbut to keep your python programs compatiblei recommend you stick to the characters in this table ps $ ss ( < ( deg + appendix |
7,086 | > / / / ae ss ae oe oe character map |
7,087 | python is still the dominant language in the world of information securityeven if the conversation about your language of choice sometimes looks more like religious war python-based tools include all manner of fuzzersproxiesand even the occasional exploit exploit frameworks like canvas are written in python as are more obscure tools like pyemu or sulley just about every fuzzer or exploit have written has been in python in factthe automotive hacking research that chris valasek and recently performed contained library to inject can messages onto your automotive network using pythonif you are interested in tinkering with information security taskspython is great language to learn because of the large number of reverse engineering and exploitation libraries available for your use now if only the metasploit developers would come to their senses and switch from ruby to pythonour community would be united in this new bookjustin covers large range of topics that an enterprising young hacker would need to get off the ground he includes walkthroughs of how to read and write network packetshow to sniff the networkas well as anything you might need for web application auditing and attacking he then spends significant time diving into how to write code to address specifics with attacking windows systems in generalblack hat python is fun readand while it might not turn you into super stunt hacker like myselfit can certainly get you started down the path rememberthe difference between script kiddies and professionals is the difference between merely using other people' tools and writing your own charlie miller st louismissouri september |
7,088 | python hacker those are two words you really could use to describe me at immunityi am lucky enough to work with people who actuallyreallyknow how to code python am not one of those people spend great deal of my time penetration testingand that requires rapid python tool developmentwith focus on execution and delivering results (not necessarily on prettinessoptimizationor even stabilitythroughout this book you will learn that this is how codebut also feel as though it is part of what makes me strong pentester hope that this philosophy and style helps you as well as you progress through the bookyou will also realize that don' take deep dives on any single topic this is by design want to give you the bare minimumwith little flavorso that you have some foundational knowledge with that in mindi've sprinkled ideas and homework assignments throughout the book to kickstart you in your own direction encourage you to explore these ideasand would love to hear back any of your own implementationstoolingor homework assignments that you have done as with any technical bookreaders at different skill levels with python (or information security in generalwill experience this book differently some of you may simply grab it and nab that are pertinent to consulting gig you are onwhile others may read it cover to cover would recommend that if you are novice to intermediate python programmer that you start at the beginning of the book and read it straight through in order you will pick up some good building blocks along the way to starti lay down some networking fundamentals in and slowly work our way through raw sockets in and using scapy in for some more interesting network tooling the next section of the book deals with hacking web applicationsstarting with your own custom tooling in and then extending the popular burp suite in from there we will spend great deal of time talking about trojansstarting with github command and control in all the way through where we will cover some windows privilege escalation tricks the final is about using volatility for automating some offensive memory forensics techniques try to keep the code samples short and to the pointand the same goes for the explanations if you are relatively new to python encourage you to punch out every line to get that coding muscle memory going all of the source code examples from this book are available at here we go |
7,089 | would like to thank my family -my beautiful wifeclareand my five childrenemilycartercohenbradyand mason -for all of the encouragement and tolerance while spent year and half of my life writing this book my brotherssistermomdadand paulette have also given me lot of motivation to keep pushing through no matter what love you all to all my folks at immunity ( would list each of you here if had the room)thanks for tolerating me on day-to-day basis you are truly an amazing crew to work with to the team at no starch -tylerbillserenaand leigh -thanks so much for all of the hard work you put into this book and the rest in your collection we all appreciate it would also like to thank my technical reviewersdan frisch and cliff janzen these guys typed out and critiqued every single line of codewrote supporting codemade editsand provided absolutely amazing support throughout the whole process anyone who is writing an infosec book should really get these guys on boardthey were amazing and then some for the rest of you ruffians that share drinkslaughs and gchatsthanks for letting me piss and moan to you about writing this book |
7,090 | environment this is the least fun -but nevertheless critical -part of the bookwhere we walk through setting up an environment in which to write and test python we are going to do crash course in setting up kali linux virtual machine (vmand installing nice ide so that you have everything you need to develop code by the end of this you should be ready to tackle the exercises and code examples in the remainder of the book before you get startedgo ahead and download and install vmware player [ also recommend that you have some windows vms at the ready as wellincluding windows xp and windows preferably -bit in both cases |
7,091 | kali is the successor to the backtrack linux distributiondesigned by offensive security from the ground up as penetration testing operating system it comes with number of tools preinstalled and is based on debian linuxso you'll also be able to install wide variety of additional tools and libraries beyond what' on the os to start firstgrab kali vm image from the following urlvmware player fire it up the default username is root and the password is toor this should get you into the full kali desktop environment as shown in figure - figure - the kali linux desktop the first thing we are going to do is ensure that the correct version of python is installed this book will use python throughout in the shell (applications>accessories>terminal)execute the followingroot@kali:~python --version python root@kali:~if you downloaded the exact image that recommended abovepython will be automatically installed please note that using different version of python might break some of the code examples in this book you have been warned |
7,092 | pip these are much like the apt package manager because they allow you to directly install python librarieswithout having to manually downloadunpackand install them let' install both of these package managers by issuing the following commandsroot@kali:~#apt-get install python-setuptools python-pip when the packages are installedwe can do quick test and install the module that we'll use in to build github-based trojan enter the following into your terminalroot@kali:~#pip install github py you should see output in your terminal indicating that the library is being downloaded and installed then drop into python shell and validate that it was installed correctlyroot@kali:~#python python (defaultmar : : [gcc on linux type "help""copyright""creditsor "licensefor more information import github exit(if your results are not identical to thesethen there is "misconfigurationin your python environment and you have brought great shame to our python dojoin this casemake sure that you followed all the steps above and that you have the correct version of kali keep in mind that for most examples throughout this bookyou can develop your code in variety of environmentsincluding maclinuxand windows there are some that are windowsspecificand 'll make sure to let you know at the beginning of the now that we have our hacking virtual machine set uplet' install python ide for development |
7,093 | while typically don' advocate commercial software productswingide is the best ide that 've used in the past seven years at immunity wingide provides all the basic ide functionality like autocompletion and explanation of function parametersbut its debugging capabilities are what set it apart from other ides will give you quick rundown of the commercial version of wingidebut of course you should choose whichever version is best for you [ you can grab wingide from that you can experience firsthand some of the features available in the commercial version you can do your development on any platform you wishbut it might be best to install wingide on your kali vm at least to get started if you've followed along with my instructions so farmake sure that you download the -bit deb package for wingideand save it to your user directory then drop into terminal and run the followingroot@kali:~dpkg - wingide - _i deb this should install wingide as planned if you get any installation errorsthere might be unmet dependencies in this casesimply runroot@kali:~apt-get - install this should fix any missing dependencies and install wingide to verify that you've installed it properlymake sure you can access it as shown in figure - |
7,094 | fire up wingide and open newblank python file then follow along as give you quick rundown of some useful features for startersyour screen should look like figure - with your main code editing area in the top left and set of tabs on the bottom |
7,095 | let' write some simple code to illustrate some of the useful functions of wingideincluding the debug probe and stack data tabs punch the following code into the editordef sum(number_one,number_two)number_one_int convert_integer(number_onenumber_two_int convert_integer(number_tworesult number_one_int number_two_int return result def convert_integer(number_string)converted_integer int(number_stringreturn converted_integer answer sum(" "," "this is very contrived examplebut it is an excellent demonstration of how to make your life easy with wingide save it with any filename you wantclick the debug menu itemand select the select current as main debug file optionas shown in figure - |
7,096 | now set breakpoint on the line of code that saysreturn converted_integer you can do this by clicking in the left margin or by hitting the key you should see little red dot appear in the margin now run the script by pressing and execution should halt at your breakpoint click the stack data tab and you should see screen like the one in figure - the stack data tab is going to show us some useful information such as the state of any local and global variables at the moment that our breakpoint was hit this allows you to debug more advanced code where you need to inspect variables during execution to track down bugs if you click the dropdown baryou can also see the current call stackwhich tells you which function called the function you are currently inside have look at figure - to see the stack trace |
7,097 | |
7,098 | we can see that convert_integer was called from the sum function on line of our python script this becomes very useful if you have recursive function calls or function that is called from many potential places using the stack data tab will come in very handy in your python developing careerthe next major feature is the debug probe tab this tab enables you to drop into python shell that is executing within the current context of the exact moment your breakpoint was hit this lets you inspect and modify variablesas well as write little snippets of test code to try out new ideas or to troubleshoot figure - demonstrates how to inspect the converted_integer variable and change its value |
7,099 | after you make some modificationsyou can resume execution of the script by pressing even though this is very simple exampleit demonstrates some of the most useful features of wingide for developing and debugging python scripts [ that' all we need in order to begin developing code for the rest of this book don' forget about making virtual machines ready as target machines for the windows-specific but of course using native hardware should not present any issues now let' get into some actual fun[ you can download vmware player from [ for "clickablelist of the links in this visit [ for comparison of features among versionsvisit [ if you already use an ide that has comparable features to wingideplease send me an email or tweet because would love to hear about it |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.