id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
6,700 | bl ackjack blackjackalso known as is card game where players try to get as close to points as possible without going over this program uses images drawn with text characterscalled ascii art american standard code for information interchange (asciiis mapping of text characters to numeric codes that computers used before unicode replaced it the playing cards in this program are an example of ascii art___ ___ | | |__a| you can find other rules and the history of this card game at en wikipedia org/wiki/blackjack |
6,701 | when you run blackjack pythe output will look like thisblackjackby al sweigart al@inventwithpython com rulestry to get as close to without going over kingsqueensand jacks are worth points aces are worth or points cards through are worth their face value ( )it to take another card ( )tand to stop taking cards on your first playyou can ( )ouble down to increase your bet but must hit exactly one more time before standing in case of tiethe bet is returned to the player the dealer stops hitting at money how much do you bet( - or quit bet dealer??___ ___ |#| |###| ##|__ player ___ ___ | | |__k|__ ( )it( )tand( )ouble down you drew of --snip-dealer ___ ___ ___ | | | |__k|__ |__ player ___ ___ ___ | | | |__k|__ |__ you won $ --snip- project # |
6,702 | the card suit symbols don' exist on your keyboardwhich is why we call the chr(function to create them the integer passed to chr(is called unicode code pointa unique number that identifies character according to the unicode standard unicode is often misunderstood howeverned batchelder' pycon us talk "pragmatic unicodeor how do stop the pain?is an excellent introduction to unicodeand you can find it at youtu be/sghbc udiqcappendix gives full list of unicode characters you can use in your python programs """blackjackby al sweigart al@inventwithpython com the classic card game also known as (this version doesn' have splitting or insurance more info at view this code at tagslargegamecard game"" import randomsys set up the constants hearts chr( character is ' diamonds chr( character is ' spades chr( character is ' clubs chr( character is ' ( list of chr codes is at backside 'backside def main() print('''blackjackby al sweigart al@inventwithpython com rules try to get as close to without going over kingsqueensand jacks are worth points aces are worth or points cards through are worth their face value ( )it to take another card ( )tand to stop taking cards on your first playyou can ( )ouble down to increase your bet but must hit exactly one more time before standing in case of tiethe bet is returned to the player the dealer stops hitting at ''' money while truemain game loop check if the player has run out of money if money < print("you're broke!" print("good thing you weren' playing with real money " print('thanks for playing!' sys exit( let the player enter their bet for this roundblackjack |
6,703 | project # print('money:'moneybet getbet(moneygive the dealer and player two cards from the deck eachdeck getdeck(dealerhand [deck pop()deck pop()playerhand [deck pop()deck pop()handle player actionsprint('bet:'betwhile truekeep looping until player stands or busts displayhands(playerhanddealerhandfalseprint(check if the player has bustif gethandvalue(playerhand break get the player' moveeither hsor dmove getmove(playerhandmoney bethandle the player actionsif move =' 'player is doubling downthey can increase their betadditionalbet getbet(min(bet(money bet))bet +additionalbet print('bet increased to {format(bet)print('bet:'betif move in (' '' ')hit/doubling down takes another card newcard deck pop(ranksuit newcard print('you drew {of {format(ranksuit)playerhand append(newcardif gethandvalue(playerhand the player has bustedcontinue if move in (' '' ')stand/doubling down stops the player' turn break handle the dealer' actionsif gethandvalue(playerhand< while gethandvalue(dealerhand the dealer hitsprint('dealer hits 'dealerhand append(deck pop()displayhands(playerhanddealerhandfalseif gethandvalue(dealerhand break the dealer has busted input('press enter to continue ' |
6,704 | print('\ \ ' show the final hands displayhands(playerhanddealerhandtrue playervalue gethandvalue(playerhand dealervalue gethandvalue(dealerhand handle whether the player wonlostor tied if dealervalue print('dealer bustsyou win ${}!format(bet) money +bet elif (playervalue or (playervalue dealervalue) print('you lost!' money -bet elif playervalue dealervalue print('you won ${}!format(bet) money +bet elif playervalue =dealervalue print('it\' tiethe bet is returned to you ' input('press enter to continue ' print('\ \ ' def getbet(maxbet) """ask the player how much they want to bet for this round "" while truekeep asking until they enter valid amount print('how much do you bet( -{}or quit)format(maxbet) bet input(''upper(strip( if bet ='quit' print('thanks for playing!' sys exit( if not bet isdecimal() continue if the player didn' enter numberask again bet int(bet if <bet <maxbet return bet player entered valid bet def getdeck() """return list of (ranksuittuples for all cards "" deck [ for suit in (heartsdiamondsspadesclubs) for rank in range( ) deck append((str(rank)suit)add the numbered cards for rank in (' '' '' '' ') deck append((ranksuit)add the face and ace cards random shuffle(deck return deck def displayhands(playerhanddealerhandshowdealerhand) """show the player' and dealer' cards hide the dealer' first blackjack |
6,705 | card if showdealerhand is false "" print( if showdealerhand print('dealer:'gethandvalue(dealerhand) displaycards(dealerhand else print('dealer???' hide the dealer' first card displaycards([backsidedealerhand[ :] show the player' cards print('player:'gethandvalue(playerhand) displaycards(playerhand def gethandvalue(cards) """returns the value of the cards face cards are worth aces are worth or (this function picks the most suitable ace value"" value numberofaces add the value for the non-ace cards for card in cards rank card[ card is tuple like (ranksuit if rank =' ' numberofaces + elif rank in (' '' '' ')face cards are worth points value + else value +int(ranknumbered cards are worth their number add the value for the aces value +numberofaces add per ace for in range(numberofaces) if another can be added with bustingdo so if value < value + return value def displaycards(cards) """display all the cards in the cards list "" rows [''''''''''the text to display on each row for icard in enumerate(cards) rows[ +___ print the top line of the card if card =backside print card' back rows[ +'|# rows[ +'|### rows[ +'| ## else print the card' front ranksuit card the card is tuple data structure project # |
6,706 | rows[ +'|{format(rank ljust( ) rows[ +'{format(suit rows[ +'| {}format(rank rjust( ' ') print each row on the screen for row in rows print(row def getmove(playerhandmoney) """asks the player for their moveand returns 'hfor hit'sfor standand 'dfor double down "" while truekeep looping until the player enters correct move determine what moves the player can make moves ['( )it''( )tand' the player can double down on their first movewhich we can tell because they'll have exactly two cards if len(playerhand= and money moves append('( )ouble down' get the player' move moveprompt 'join(moves' move input(movepromptupper( if move in (' '' ') return move player has entered valid move if move ='dand '( )ouble downin moves return move player has entered valid move if the program is run (instead of imported)run the game if __name__ ='__main__' main(after entering the source code and running it few timestry making experimental changes to it blackjack has several custom rules that you could implement for exampleif the first two cards have the same valuea player can split them into two hands and wager on them separately alsoif the player receives "blackjack(the ace of spades and black jackfor their first two cardsthe player wins ten-to-one payout you can find out more about the game from 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 how can you make the player start with different amount of money how does the program prevent the player from betting more money than they haveblackjack |
6,707 | how does the program represent hand of cards what do each of the strings in the rows list (created on line represent what happens if you delete or comment out random shuffle(deckon line what happens if you change money -bet on line to money +bet what happens when showdealerhand in the displayhands(function is set to truewhat happens when it is false project # |
6,708 | bouncing dvd logo if you are of certain ageyou'll remember those ancient technological devices called dvd players when not playing dvdsthey would display diagonally traveling dvd logo that bounced off the edges of the screen this program simulates this colorful dvd logo by making it change direction each time it hits an edge we'll also keep track of how many times logo hits corner of the screen this creates an interesting visual animation to look atespecially for the magical moment when logo lines up perfectly with corner |
6,709 | run from the command prompt or terminal in order to display correctly you can find more information about the bext module at project/bextthe program in action when you run bouncingdvd pythe output will look like figure - figure - the diagonally moving dvd logos of the bouncingdvd py program how it works you may remember cartesian coordinates from your math class in school in programmingthe -coordinate represents an object' horizontal position and the -coordinate represents its vertical positionjust like in mathematics howeverunlike in mathematicsthe origin point ( is in the upper-left corner of the screenand the -coordinate increases as you go down the -coordinate increases as the object moves rightjust like in mathematics figure - shows the coordinate system for your screen project # |
6,710 | ( , increases ( , ( , ( , figure - the origin point ( is in the upper left of the screenwhile the xand -coordinates increase going right and downrespectively the bext module' goto(function works the same waycalling bext goto ( places the text cursor at the top left of the terminal window we represent each bouncing dvd logo using python dictionary with the keys 'color''direction'' 'and 'ythe values for the 'xand 'yare integers representing the logo' position in the window since these values get passed to bext goto()increasing them will move the logo right and downwhile decreasing them will move the logo left and up """bouncing dvd logoby al sweigart al@inventwithpython com bouncing dvd logo animation you have to be "of certain ageto appreciate this press ctrl- to stop notedo not resize the terminal window while this program is running view this code at tagsshortartisticbext"" import sysrandomtime try import bext except importerror print('this program requires the bext modulewhich you' print('can install by following the instructions at' print(' sys exit( set up the constants widthheight bext size(bouncing dvd logo |
6,711 | newline automaticallyso reduce the width by one width - number_of_logos (!try changing this to or pause_amount (!try changing this to or (!try changing this list to fewer colors colors ['red''green''yellow''blue''magenta''cyan''white' up_right 'ur up_left 'ul down_right 'dr down_left 'dl directions (up_rightup_leftdown_rightdown_left key names for logo dictionaries color 'color ' ' dir 'direction def main() bext clear( generate some logos logos [ for in range(number_of_logos) logos append({colorrandom choice(colors) xrandom randint( width ) yrandom randint( height ) dirrandom choice(directions)} if logos[- ][ = make sure is even so it can hit the corner logos[- ][ - cornerbounces count how many times logo hits corner while truemain program loop for logo in logoshandle each logo in the logos list erase the logo' current location bext goto(logo[ ]logo[ ] print('end=''(!try commenting this line out originaldirection logo[dir see if the logo bounces off the corners if logo[ = and logo[ = logo[dirdown_right cornerbounces + elif logo[ = and logo[ =height logo[dirup_right cornerbounces + elif logo[ =width and logo[ = logo[dirdown_left cornerbounces + project # |
6,712 | elif logo[ =width and logo[ =height logo[dirup_left cornerbounces + see if the logo bounces off the left edgeelif logo[ = and logo[dir=up_leftlogo[dirup_right elif logo[ = and logo[dir=down_leftlogo[dirdown_right see if the logo bounces off the right edge(width because 'dvdhas letters elif logo[ =width and logo[dir=up_rightlogo[dirup_left elif logo[ =width and logo[dir=down_rightlogo[dirdown_left see if the logo bounces off the top edgeelif logo[ = and logo[dir=up_leftlogo[dirdown_left elif logo[ = and logo[dir=up_rightlogo[dirdown_right see if the logo bounces off the bottom edgeelif logo[ =height and logo[dir=down_leftlogo[dirup_left elif logo[ =height and logo[dir=down_rightlogo[dirup_right if logo[dir!originaldirectionchange color when the logo bounceslogo[colorrandom choice(colorsmove the logo ( moves by because the terminal characters are twice as tall as they are wide if logo[dir=up_rightlogo[ + logo[ - elif logo[dir=up_leftlogo[ - logo[ - elif logo[dir=down_rightlogo[ + logo[ + elif logo[dir=down_leftlogo[ - logo[ + display number of corner bouncesbext goto( bext fg('white'print('corner bounces:'cornerbouncesend=''for logo in logosdraw the logos at their new locationbouncing dvd logo |
6,713 | bext goto(logo[ ]logo[ ] bext fg(logo[color] print('dvd'end='' bext goto( sys stdout flush((required for bext-using programs time sleep(pause_amount if this program was run (instead of imported)run the game if __name__ ='__main__' try main( except keyboardinterrupt print( print('bouncing dvd logoby al sweigart' sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingchange number_of_logos to increase the number of bouncing logos on the screen change pause_amount to speed up or slow down the logos 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 widthheight bext size(on line to widthheight what happens if you replace dirrandom choice(directionson line with dirdown_right how can you make the 'corner bounces:text not appear on the screen what error message do you get if you delete or comment out cornerbounces on line project # |
6,714 | caesar cipher the caesar cipher is an ancient encryption algorithm used by julius caesar it encrypts letters by shifting them over by certain number of places in the alphabet we call the length of shift the key for exampleif the key is then becomes db becomes ec becomes fand so on to decrypt the messageyou must shift the encrypted letters in the opposite direction this program lets the user encrypt and decrypt messages according to this algorithm in modern timesthe caesar cipher isn' very sophisticatedbut that makes it ideal for beginners the program in project "caesar hacker,can brute-force through all possible keys to decrypt messageseven if you don' know the original key alsoif you encrypt the message with the key the caesar cipher becomes identical to project "rot cipher |
6,715 | cipher if you' like to learn about ciphers and code breaking in generalyou can read my book cracking codes with python (no starch press nostarch com/crackingcodes/the program in action when you run caesarcipher pythe output will look like thiscaesar cipherby al sweigart al@inventwithpython com do you want to ( )ncrypt or ( )ecrypte please enter the key ( to to use enter the message to encrypt meet me by the rose bushes tonight qiix qi fc xli vswi fywliw xsrmklx full encrypted text copied to clipboard caesar cipherby al sweigart al@inventwithpython com do you want to ( )ncrypt or ( )ecryptd please enter the key ( to to use enter the message to decrypt qiix qi fc xli vswi fywliw xsrmklx meet me by the rose bushes tonight full decrypted text copied to clipboard how it works like most cipher programsthe caesar cipher works by translating characters into numbersperforming some math operations on those numbersand translating the numbers back into text characters in the context of cipherswe call these text characters symbols symbols can include lettersnumeric digitsand punctuation markseach of which gets assigned unique integer in the case of the caesar cipher programthe symbols are all lettersand their integers are their position in the symbols string'abcdefghijklmnopqrstuvwxyz """caesar cipherby al sweigart al@inventwithpython com the caesar cipher is shift cipher that uses addition and subtraction to encrypt and decrypt letters more info at view this code at tagsshortbeginnercryptographymath"" try import pyperclip pyperclip copies text to the clipboard except importerror pass if pyperclip is not installeddo nothing it' no big deal project # |
6,716 | every possible symbol that can be encrypted/decrypted (!you can add numbers and punctuation marks to encrypt those symbols as well symbols 'abcdefghijklmnopqrstuvwxyz print('caesar cipherby al sweigart al@inventwithpython com' print('the caesar cipher encrypts letters by shifting them over by ' print('key number for examplea key of means the letter is' print('encrypted into cthe letter encrypted into dand so on ' print( let the user enter 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(' ') mode 'encrypt break elif response startswith(' ') mode 'decrypt break print('please enter the letter or ' let the user enter the key to use while truekeep asking until the user enters valid key maxkey len(symbols print('please enter the key ( to {}to use format(maxkey) response input(''upper( if not response isdecimal() continue if <int(responselen(symbols) key int(response break let the user enter the message to encrypt/decrypt print('enter the message to {format(mode) message input('' caesar cipher only works on uppercase letters message message upper( stores the encrypted/decrypted form of the message translated ' encrypt/decrypt each symbol in the message for symbol in message if symbol in symbols get the encrypted (or decryptednumber for this symbol num symbols find(symbolget the number of the symbol if mode ='encrypt' num num key elif mode ='decrypt' num num key caesar cipher |
6,717 | handle the wrap-around if num is larger than the length of symbols or less than if num >len(symbols) num num len(symbols elif num num num len(symbols add encrypted/decrypted number' symbol to translated translated translated symbols[num else just add the symbol without encrypting/decrypting translated translated symbol display the encrypted/decrypted string to the screen print(translated try pyperclip copy(translated print('full {}ed text copied to clipboard format(mode) except pass do nothing if pyperclip wasn' installed 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 you can expand the encryptable symbols by adding characters to the symbols string 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 symbols 'abcdefghijklmnopqrstuvwxyzon line to symbols 'abc' what happens when you encrypt message with key what error message do you get if you delete or comment out translated 'on line what error message do you get if you delete or comment out key int(responseon line what happens if you change translated translated symbols[numon line to translated translated symbol project # |
6,718 | caesar hacker this program can hack messages encrypted with the caesar cipher from project even if you don' know the key there are only possible keys for the caesar cipherso computer can easily try all possible decryptions and display the results to the user in cryptographywe call this technique brute-force attack if you' like to learn more about ciphers and code breakingyou can read my book cracking codes with python (no starch press |
6,719 | when you run caesarhacker pythe output will look like thiscaesar cipher hackerby al sweigart al@inventwithpython com enter the encrypted caesar cipher message to hack qiix qi fc xli vswi fywliw xsrmklx key # qiix qi fc xli vswi fywliw xsrmklx key # phhw ph eb wkh urvh exvkhv wrqljkw key # oggv og da vjg tqug dwujgu vqpkijv key # nffu nf cz uif sptf cvtift upojhiu key # meet me by the rose bushes tonight key # ldds ld ax sgd qnrd atrgdr snmhfgs key # kccr kc zw rfc pmqc zsqfcq rmlgefr --snip-how it works note that lines to in this program are nearly identical to lines to in the caesar cipher program the hacking program implements the same decryption codeexcept that it does so in for loopwhich runs the code for every possible key unfortunatelythe hacking program isn' sophisticated enough to identify when it has found the correct key it relies on human to read the output and identify which decryption produced the original english (or whichever written language was encrypted of the book cracking codes with python (no starch press details how you can write python code to detect english messages """caesar cipher hackerby al sweigart al@inventwithpython com this program hacks messages encrypted with the caesar cipher by doing brute force attack against every possible key more info at view this code at tagstinybeginnercryptographymath"" print('caesar cipher hackerby al sweigart al@inventwithpython com' let the user specify the message to hack print('enter the encrypted caesar cipher message to hack ' message input('' every possible symbol that can be encrypted/decrypted (this must match the symbols used when encrypting the message symbols 'abcdefghijklmnopqrstuvwxyz for key in range(len(symbols))loop through every possible key translated ' decrypt each symbol in the message for symbol in message project # |
6,720 | if symbol in symbolsnum symbols find(symbolget the number of the symbol num num key decrypt the number handle the wrap-around if num is less than if num num num len(symbolsadd decrypted number' symbol to translatedtranslated translated symbols[numelsejust add the symbol without decryptingtranslated translated symbol display the key being testedalong with its decrypted textprint('key #{}{}format(keytranslated)after entering the source code and running it few timestry making experimental changes to it keep in mind that the string stored in the symbols variable must match the symbols variable in the caesar cipher program that produced the encrypted text exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what error message do you get if you delete or comment out translated 'on line what happens if you change translated translated symbols[numon line to translated translated symbol what happens if you enter an unencrypted message into the caesar cipher hacker programcaesar hacker |
6,721 | calendar maker this program generates printable text files of monthly calendars for the month and year you enter dates and calendars are tricky topic in programming because there are so many different rules for determining the number of days in monthwhich years are leap yearsand which day of the week particular date falls on fortunatelypython' datetime module handles these details for you this program focuses on generating the multiline string for the monthly calendar page |
6,722 | when you run calendarmaker pythe output will look like thiscalendar makerby al sweigart al@inventwithpython com enter the year for the calendar enter the month for the calendar - december sunday monday tuesday wednesday thursday friday saturday +++++++| | | | | | +++++++ +++++++ | | | | | | +++++++| | | | | | | +++++++| | | | | | | +++++++| | +++++++saved to calendar_ txt how it works note that the getcalendarfor(function returns giant multiline string of the calendar for the given month and year in this functionthe caltext variable stores this stringwhich adds the linesspacesand dates to it to track the datethe currentdate variable holds datetime date(objectwhich gets calendar maker |
6,723 | timedelta(objects you can learn about python' date and time modules by reading of automate the boring stuff with python at automatetheboringstuff com/ / """calendar makerby al sweigart al@inventwithpython com create monthly calendarssaved to text file and fit for printing view this code at tagsshort"" import datetime set up the constants days ('sunday''monday''tuesday''wednesday''thursday' 'friday''saturday' months ('january''february''march''april''may''june''july' 'august''september''october''november''december' print('calendar makerby al sweigart al@inventwithpython com' while trueloop to get year from the user print('enter the year for the calendar:' response input('' if response isdecimal(and int(response year int(response break print('please enter numeric yearlike ' continue while trueloop to get month from the user print('enter the month for the calendar - :' response input('' if not response isdecimal() print('please enter numeric monthlike for march ' continue month int(response if <month < break print('please enter number from to ' def getcalendarfor(yearmonth) caltext 'caltext will contain the string of our calendar put the month and year at the top of the calendar caltext +( months[month str(year'\ add the days of the week labels to the calendar (!try changing this to abbreviationssunmontueetc project # |
6,724 | caltext +sunday monday tuesday wednesday thursday friday saturday \ the horizontal line string that separate weeks weekseparator ('+ '+\ the blank rows have ten spaces in between the day separators blankrow (' '|\ get the first date in the month (the datetime module handles all the complicated calendar stuff for us here currentdate datetime date(yearmonth roll back currentdate until it is sunday (weekday(returns for sundaynot while currentdate weekday(! currentdate -datetime timedelta(days= while trueloop over each week in the month caltext +weekseparator daynumberrow is the row with the day number labels daynumberrow ' for in range( ) daynumberlabel str(currentdate dayrjust( daynumberrow +'|daynumberlabel ( currentdate +datetime timedelta(days= go to next day daynumberrow +'|\nadd the vertical line after saturday add the day number row and blank rows to the calendar text caltext +daynumberrow for in range( )(!try changing the to or caltext +blankrow check if we're done with the month if currentdate month !month break add the horizontal line at the very bottom of the calendar caltext +weekseparator return caltext caltext getcalendarfor(yearmonth print(caltextdisplay the calendar save the calendar to text file calendarfilename 'calendar_{} {txtformat(yearmonth with open(calendarfilename' 'as fileobj fileobj write(caltext print('saved to calendarfilenamecalendar maker |
6,725 | this program from scratch without looking at the source code in this book it doesn' have to be exactly the same as this programyou can invent your own versionon your ownyou can also try to figure out how to do the followingadd text inside some of the boxes for holidays add text inside some of the boxes for reoccurring events print "minicalendar that has dates without boxes 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 how can you make the calendar display abbreviated monthsfor exampleshow 'janinstead of 'january' what error message do you get if you delete or comment out year int (responseon line how can you make the calendar not display the days of the week at the top how can you make the program not save the calendar to file what happens if you delete or comment out print(caltexton line project # |
6,726 | carrot in box this is simple and silly bluffing game for two human players each player has box one box has carrot in itand each player wants to have the carrot the first player looks in their box and then tells the second player they either do or don' have the carrot the second player gets to decide whether to swap boxes or not the ascii art in the code makes typing this program take while (though copying and pasting the ascii art can speed up the task)but this project is good for beginners because it is straightforwardwith minimal looping and no defined functions |
6,727 | when you run carrotinabox pythe output will look like thiscarrot in boxby al sweigart al@inventwithpython com --snip-human player enter your namealice human player enter your namebob here are two boxes//++red gold box box ++++alice bob aliceyou have red box in front of you bobyou have gold box in front of you press enter to continue --snip-when bob has closed their eyespress enter alice here is the inside of your box___vv____ vv vv |___||____|//++red gold box box ++++(carrot!alice bob press enter to continue --snip-how it works this program relies on the second player closing their eyes so they don' see the contents of the first player' box in order to keep the second player from seeing the box contents after this stepwe need to find way to clear the screen line does this with print('\ this prints newline characterscausing the previously printed content to scroll up and out of view this keeps the second player from accidentally seeing what was only intended for the first player while the second player could always scroll up to see this textit' be obvious to the first playerwho' sitting right next to themthat they had done so on lines and the spacing of the vertical lines may look incorrectbut the program replaces the curly braces with the string 'red project # |
6,728 | will cause the rest of the box' vertical lines to line up with the rest of the ascii-art image """carrot in boxby al sweigart al@inventwithpython com silly bluffing game between two human players based on the game from the show out of cats view this code at tagslargebeginnergametwo-player"" import random print('''carrot in boxby al sweigart al@inventwithpython com this is bluffing game for two human players each player has box one box has carrot in it to winyou must have the box with the carrot in it this is very simple and silly game the first player looks into their box (the second player must close their eyes during thisthe first player then says "there is carrot in my boxor "there is not carrot in my boxthe second player then gets to decide if they want to swap boxes or not ''' input('press enter to begin ' name input('human player enter your name' name input('human player enter your name' playernames name[: center( name[: center( print('''here are two boxes // ++ red gold box box ++++/''' print( print(playernames print( print( name 'you have red box in front of you ' print( name 'you have gold box in front of you ' print( print( name 'you will get to look into your box ' print( name upper('close your eyes and don\' look!!!' input('when name has closed their eyespress enter ' print( print( name here is the inside of your box:' if random randint( = carrotinfirstbox true carrot in box |
6,729 | carrotinfirstbox false if carrotinfirstbox print('' ___vv____ vv vv |___||____ |// ++ red gold box box ++++ (carrot!)''' print(playernames else print('' | // ++ red gold box box ++++ (no carrot!)''' print(playernames input('press enter to continue ' print('\ clear the screen by printing several newlines print( name 'tell name to open their eyes ' input('press enter to continue ' print( print( name 'say one of the following sentences to name ' print( there is carrot in my box ' print( there is not carrot in my box ' print( input('then press enter to continue ' print( print( name 'do you want to swap boxes with name 'yes/no' while true response input(''upper( if not (response startswith(' 'or response startswith(' ')) print( name 'please enter "yesor "no' else break firstbox 'red note the space after the " project # |
6,730 | if response startswith(' ') carrotinfirstbox not carrotinfirstbox firstboxsecondbox secondboxfirstbox print('''here are the two boxes // ++ {{ box box ++++/''format(firstboxsecondbox) print(playernames input('press enter to reveal the winner ' print( if carrotinfirstbox print('' ___vv____ vv vv |___||____| |// ++ {{ box box ++++/''format(firstboxsecondbox) else print('' ___vv____ vv vv ||___||____ /|/ ++ {{ box box ++++/''format(firstboxsecondbox) print(playernames this modification made possible through the 'carrotinfirstboxvariable if carrotinfirstbox print( name is the winner!' else print( name is the winner!' print('thanks for playing!'carrot in box |
6,731 | experimental changes to it on your ownyou can also try to figure out how to do the followingchange the ascii art for the boxes and carrots to something more ornate add "would you like to play again?feature that lets the players play again while keeping score add third player that the second player must bluff to 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 note that line has the code name[: and name[: enter name longer than letters what do you notice about how the program displays this name what happens if you omit the space at the end of firstbox 'red on line what happens if you delete or comment out print('\ on line what happens if you delete or comment out the elseon line and break on line project # |
6,732 | cho-han cho-han is dice game played in gambling houses of feudal japan two six-sided dice are rolled in cupand gamblers must guess if the sum is even (choor odd (hanthe house takes small cut of all winnings the simple random number generation and basic math used to determine odd or even sums make this project especially suitable for beginners more information about cho-han can be found at cho-han |
6,733 | when you run chohan pythe output will look like thischo-hanby al sweigart al@inventwithpython com in this traditional japanese dice gametwo dice are rolled in bamboo cup by the dealer sitting on the floor the player must guess if the dice total to an even (choor odd (hannumber you have mon how much do you bet(or quit the dealer swirls the cup and you hear the rattle of dice the dealer slams the cup on the floorstill covering the dice and asks for your bet cho (evenor han (odd)cho the dealer lifts the cup to revealgo go you wonyou take mon the house collects mon fee --snip-how it works the random randint( call returns random integer between and making it ideal for representing six-sided die roll howeverwe also need to display the japanese words for the numbers one to six instead of having an if statement followed by five elif statementswe have dictionarystored in japanese_numbersthat maps the integers to to strings of the japanese words this is how line ' japanese_numbers[dice and japanese_numbers[dice can display the japanese words for the dice results in just one line of code """cho-hanby al sweigart al@inventwithpython com the traditional japanese dice game of even-odd view this code at tagsshortbeginnergame"" import randomsys japanese_numbers { 'ichi' 'ni' 'san' 'shi' 'go' 'roku' print('''cho-hanby al sweigart al@inventwithpython com in this traditional japanese dice gametwo dice are rolled in bamboo cup by the dealer sitting on the floor the player must guess if the dice total to an even (choor odd (hannumber ''' purse project # |
6,734 | place your bet print('you have'purse'mon how much do you bet(or quit)' while true pot input('' if pot upper(='quit' print('thanks for playing!' sys exit( elif not pot isdecimal() print('please enter number ' elif int(potpurse print('you do not have enough to make that bet ' else this is valid bet pot int(potconvert pot to an integer break exit the loop once valid bet is placed roll the dice dice random randint( dice random randint( print('the dealer swirls the cup and you hear the rattle of dice ' print('the dealer slams the cup on the floorstill covering the' print('dice and asks for your bet ' print( print(cho (evenor han (odd)?' let the player bet cho or han while true bet input(''upper( if bet !'choand bet !'han' print('please enter either "choor "han' continue else break reveal the dice results print('the dealer lifts the cup to reveal:' print('japanese_numbers[dice ]'-'japanese_numbers[dice ] print('dice '-'dice determine if the player won rolliseven (dice dice = if rolliseven correctbet 'cho else correctbet 'han playerwon bet =correctbet display the bet results if playerwon print('you wonyou take'pot'mon ' purse purse pot add the pot from player' purse print('the house collects 'pot / 'mon fee 'cho-han |
6,735 | purse purse (pot / the house fee is elsepurse purse pot subtract the pot from player' purse print('you lost!'check if the player has run out of moneyif purse = print('you have run out of money!'print('thanks for playing!'sys exit(after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingimplement one of the variations of this gamedescribed in the wikipedia articlewhere multiple players bet against each other add computer-controlled gamblers with their own purses to play against add extra bonuses for certain rollssuch as or snake eyes allow the player to bet on specific number to get bonus to their wager 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 how can you make the player start with different amount of money how does the program prevent the player from betting more money than they have how does the program know if the sum of the two dice is even or odd what happens if you change random randint( on line to random randint( ) does the house still collect percent fee if you change pot / on line (not line to what happens if you delete or comment out lines and project # |
6,736 | clickbait he adline at our website needs to trick people into looking at advertisementsbut coming up with creativeoriginal content is too hard luckilywith the clickbait headline generatorwe can make computer come up with millions of outrageous fake headlines they're all low qualitybut readers don' seem to mind this program generates as many headlines as you need from mad libs-style template there' lot of text in this program for the headline templatesbut the code itself is straightforward and suitable for beginners |
6,737 | when you run clickbait pythe output will look like thisclickbait headline generator by al sweigart al@inventwithpython com our website needs to trick people into looking at adsenter the number of clickbait headlines to generate big companies hate himsee how this new york cat invented cheaper robot what telephone psychics don' want you to know about avocados you won' believe what this north carolina shovel found in her workplace --snip- reasons why parents are more interesting than you think (number will surprise you!what robots don' want you to know about cats this florida telephone psychic didn' think robots would take her job she was wrong how it works this program has several functions for generating different kinds of clickbait headlines each of them gets random words from statesnounsplaceswhenand other lists the functions then insert these words into template string with the format(string method before returning this string this is like "mad libsactivity bookexcept the computer fills in the blanksallowing the program to generate thousands of clickbait headlines in seconds """clickbait headline generatorby al sweigart al@inventwithpython com clickbait headline generator for your soulless content farm website view this code at tagslargebeginnerhumorword"" import random set up the constants object_pronouns ['her''him''them' possesive_pronouns ['her''his''their' personal_pronouns ['she''he''they' states ['california''texas''florida''new york''pennsylvania' 'illinois''ohio''georgia''north carolina''michigan' nouns ['athlete''clown''shovel''paleo diet''doctor''parent' 'cat''dog''chicken''robot''video game''avocado' 'plastic straw','serial killer''telephone psychic' places ['house''attic''bank deposit box''school''basement' 'workplace''donut shop''apocalypse bunker' when ['soon''this year''later today''right now''next week' def main() print('clickbait headline generator' print('by al sweigart al@inventwithpython com' project # |
6,738 | print( print('our website needs to trick people into looking at ads!' while true print('enter the number of clickbait headlines to generate:' response input('' if not response isdecimal() print('please enter number ' else numberofheadlines int(response break exit the loop once valid number is entered for in range(numberofheadlines) clickbaittype random randint( if clickbaittype = headline generatearemillennialskillingheadline( elif clickbaittype = headline generatewhatyoudontknowheadline( elif clickbaittype = headline generatebigcompanieshateherheadline( elif clickbaittype = headline generateyouwontbelieveheadline( elif clickbaittype = headline generatedontwantyoutoknowheadline( elif clickbaittype = headline generategiftideaheadline( elif clickbaittype = headline generatereasonswhyheadline( elif clickbaittype = headline generatejobautomatedheadline( print(headline print( website random choice(['wobsite''blag''facebuuk''googles' 'facesbook''tweedie''pastagram'] when random choice(whenlower( print('post these to our'websitewhen'or you\'re fired!' each of these functions returns different type of headline def generatearemillennialskillingheadline() noun random choice(nouns return 'are millennials killing the {industry?format(noun def generatewhatyoudontknowheadline() noun random choice(nouns pluralnoun random choice(nouns' when random choice(when return 'without this {}{could kill you {}format(nounpluralnounwhen def generatebigcompanieshateherheadline()clickbait headline generator |
6,739 | pronoun random choice(object_pronounsstate random choice(statesnoun random choice(nounsnoun random choice(nounsreturn 'big companies hate {}see how this {{invented cheaper {}format(pronounstatenoun noun def generateyouwontbelieveheadline() state random choice(states noun random choice(nouns pronoun random choice(possesive_pronouns place random choice(places return 'you won\' believe what this {{found in {{}format(statenounpronounplace def generatedontwantyoutoknowheadline() pluralnoun random choice(nouns' pluralnoun random choice(nouns' return 'what {don\' want you to know about {}format(pluralnoun pluralnoun def generategiftideaheadline() number random randint( noun random choice(nouns state random choice(states return '{gift ideas to give your {from {}format(numbernounstate def generatereasonswhyheadline() number random randint( pluralnoun random choice(nouns' number should be no larger than number number random randint( number return '{reasons why {are more interesting than you think (number {will surprise you!)format(number pluralnounnumber def generatejobautomatedheadline() state random choice(states noun random choice(nouns random randint( pronoun possesive_pronouns[ pronoun personal_pronouns[ if pronoun ='their' return 'this {{didn\' think robots would take {job {were wrong format(statenounpronoun pronoun else return 'this {{didn\' think robots would take {job {was wrong format(statenounpronoun pronoun project # |
6,740 | 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 followingadd additional types of clickbait headlines add new categories of wordsbeyond nounsstatesand so on exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what error message do you get if you delete or comment out numberof headlines int(responseon line what error message do you get if you change int(responseto response on line what error message do you get if you change line to when []clickbait headline generator |
6,741 | at eq the collatz sequencealso called the problemis the simplest impossible math problem (but don' worrythe program itself is easy enough for beginners from starting numbernfollow three rules to get the next number in the sequence if is eventhe next number is if is oddthe next number is if is stop otherwiserepeat it is generally thoughtbut so far not mathematically proventhat every starting number eventually terminates at more information about the collatz sequence can be found at collatz_conjecture |
6,742 | when you run collatz pythe output will look like thiscollatz sequenceorthe problem by al sweigart al@inventwithpython com the collatz sequence is sequence of numbers produced from starting number nfollowing three rules--snip-enter starting number (greater than or quit collatz sequenceorthe problem by al sweigart al@inventwithpython com --snip-enter starting number (greater than or quit how it works the mod operator can help you determine if number is even or odd remember that this operator is sort of "remainderoperator while divided by is -remainder- mod is simply even numbers divided by have no remainderwhile odd numbers divided by have remainder of when is eventhe condition in if = on line evaluates to true when is oddit evaluates to false """collatz sequenceby al sweigart al@inventwithpython com generates numbers for the collatz sequencegiven starting number more info at view this code at tagstinybeginnermath"" import systime print('''collatz sequenceorthe problem by al sweigart al@inventwithpython com the collatz sequence is sequence of numbers produced from starting number nfollowing three rules if is eventhe next number is if is oddthe next number is collatz sequence |
6,743 | it is generally thoughtbut so far not mathematically proventhat every starting number eventually terminates at ''' print('enter starting number (greater than or quit:' response input('' if not response isdecimal(or response =' ' print('you must enter an integer greater than ' sys exit( int(response print(nend=''flush=true while ! if = if is even / elseotherwisen is odd print('str( )end=''flush=true time sleep( print(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 how many numbers are in collatz sequence that begins with how many numbers are in collatz sequence that begins with are the collatz sequences for starting numbers that are powers of two ( on so onalways composed of only even numbers (aside from the final ) what happens when you enter for the starting integer project # |
6,744 | ay conway' game of life is cellular automata simulation that follows simple rules to create interesting patterns it was invented by mathematician john conway in and popularized by martin gardner' "mathematical gamescolumn in scientific american todayit' favorite among programmers and computer scientiststhough it' more an interesting visualization than true "game the twodimensional board has grid of "cells,each of which follows three simple rulesliving cells with two or three neighbors stay alive in the next step of the simulation dead cells with exactly three neighbors become alive in the next step of the simulation any other cell dies or stays dead in the next step of the simulation |
6,745 | any older states there is large body of research regarding the patterns that these simple rules produce tragicallyprofessor conway passed away of complications from covid- in april more information about conway' game of life can be found at conway% s_game_of_lifeand more information about martin gardner at the program in action when you run conwaysgameoflife pythe output will look like thiso oo oo oo oo oo oo oo oo ooo oo ooo oo oo oo oo oo oooo oo ooo oooo oo oo oo oo oo ooo oo oooo oo oo oo oo ooo oo ooo ooooo oooo how it works the state of the cells is stored in dictionaries in the cells and nextcells variables both dictionaries have (xytuples for keys (where and are integers)'ofor living cellsand for dead cells lines to are set up to print representation of these dictionaries onto the screen the cells variable' dictionary represents the current state of the cellswhile nextcells stores the dictionary for the cells in the next step in the simulation """conway' game of lifeby al sweigart al@inventwithpython com the classic cellular automata simulation press ctrl- to stop more info at view this code at tagsshortartisticsimulation"" import copyrandomsystime set up the constants width the width of the cell grid height the height of the cell grid (!try changing alive to '#or another character project # |
6,746 | (!try changing dead to or another character dead the character representing dead cell (!try changing alive to '|and dead to '- the cells and nextcells are dictionaries for the state of the game their keys are (xytuples and their values are one of the alive or dead values nextcells { put random dead and alive cells into nextcells for in range(width)loop over every possible column for in range(height)loop over every possible row / chance for starting cells being alive or dead if random randint( = nextcells[(xy)alive add living cell else nextcells[(xy)dead add dead cell while truemain program loop each iteration of this loop is step of the simulation print('\ separate each step with newlines cells copy deepcopy(nextcells print cells on the screen for in range(height) for in range(width) print(cells[(xy)]end=''print the or space print(print newline at the end of the row print('press ctrl- to quit ' calculate the next step' cells based on current step' cells for in range(width) for in range(height) get the neighboring coordinates of (xy)even if they wrap around the edge left ( width right ( width above ( height below ( height count the number of living neighbors numneighbors if cells[(leftabove)=alive numneighbors + top-left neighbor is alive if cells[(xabove)=alive numneighbors + top neighbor is alive if cells[(rightabove)=alive numneighbors + top-right neighbor is alive if cells[(lefty)=alive numneighbors + left neighbor is alive if cells[(righty)=alive numneighbors + right neighbor is alive if cells[(leftbelow)=aliveconway' game of life |
6,747 | numneighbors + bottom-left neighbor is alive if cells[(xbelow)=alivenumneighbors + bottom neighbor is alive if cells[(rightbelow)=alivenumneighbors + bottom-right neighbor is alive set cell based on conway' game of life rulesif cells[(xy)=alive and (numneighbors = or numneighbors = )living cells with or neighbors stay alivenextcells[(xy)alive elif cells[(xy)=dead and numneighbors = dead cells with neighbors become alivenextcells[(xy)alive elseeverything else dies or stays deadnextcells[(xy)dead trytime sleep( add second pause to reduce flickering except keyboardinterruptprint("conway' game of life"print('by al sweigart al@inventwithpython com'sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingadjust the percentage of cells that start as livinginstead of always using percent add the ability to read in the initial state from text fileso the user can edit the starting cell states manually 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 when you change width on line to width what happens if you delete or comment out print('\ on line what happens if you change random randint( on line to random randint( ) what happens if you change nextcells[(xy)dead on line to nextcells[(xy)alive project # |
6,748 | countdown this program displays digital timer that counts down to zero rather than ender numeric characters directlythe sevseg py module from project "seven-segment display module,generates the drawings for each digit you must create this file before the countdown program can work thenset the countdown timer to any number of secondsminutesand hours you like this program is similar to project "digital clock |
6,749 | when you run countdown pythe output will look like this__ __ |__|____ __ |__|____ __ __|__|__ __press ctrl- to quit how it works after running import sevsegyou can call the sevseg getsevsegstr(function to get multiline string of the seven segment digits howeverthe countdown program needs to display colon made out of asterisks in between the hoursminutesand seconds this requires splitting up the three lines of the multiline strings for these digits into three separate strings with the splitlines(method """countdownby al sweigart al@inventwithpython com show countdown timer animation using seven-segment display press ctrl- to stop more info at requires sevseg py to be in the same folder view this code at tagstinyartistic"" import systime import sevseg imports our sevseg py program (!change this to any number of seconds secondsleft try while truemain program loop clear the screen by printing several newlines print('\ get the hours/minutes/seconds from secondsleft for example is hours minute seconds so / is hours hours str(secondsleft / and is and / is minute minutes str((secondsleft / and is seconds seconds str(secondsleft get the digit strings from the sevseg module hdigits sevseg getsevsegstr(hours htoprowhmiddlerowhbottomrow hdigits splitlines( mdigits sevseg getsevsegstr(minutes mtoprowmmiddlerowmbottomrow mdigits splitlines( project # |
6,750 | sdigits sevseg getsevsegstr(seconds stoprowsmiddlerowsbottomrow sdigits splitlines( display the digits print(htoprow mtoprow stoprow print(hmiddlerow mmiddlerow smiddlerow print(hbottomrow mbottomrow sbottomrow if secondsleft = print( print(boom *' break print( print('press ctrl- to quit ' time sleep( insert one-second pause secondsleft - except keyboardinterrupt print('countdownby al sweigart al@inventwithpython com' sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingprompt the user to enter the starting countdown time let the user enter message to display at the end of the countdown 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 secondsleft on line to secondsleft what happens if you change the on lines and to what happens if you change time sleep( on line to time sleep( ) what happens if you change secondsleft - on line to secondsleft - what happens if you delete or comment out print('\ on line what error message do you get if you delete or comment out import sevseg on line countdown |
6,751 | deep cav this program is an animation of deep cave that descends forever into the earth although shortthis program takes advantage of the scrolling nature of the computer screen to produce an interesting and unending visualizationproof that it doesn' take much code to produce something fun to watch this program is similar to project "rainbow |
6,752 | when you run deepcave pythe output will look like thisdeep caveby al sweigart al@inventwithpython com press ctrl- to stop ###########################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################--snip-how it works this program takes advantage of the fact that printing new lines eventually causes the previous lines to move up the screen by printing slightly different gap on each linethe program creates scrolling animation that looks like the viewer is moving downward the number of hashtag characters on the left side is tracked by the leftwidth variable the number of spaces in the middle is tracked by the gapwidth variable the number of hashtag characters on the right side is calculated from width gapwidth leftwidth this ensures that each line is always the same width """deep caveby al sweigart al@inventwithpython com an animation of deep cave that goes forever into the earth view this code at tagstinybeginnerscrollingartistic"" import randomsystime set up the constants width (!try changing this to or pause_amount (!try changing this to or print('deep caveby al sweigart al@inventwithpython com' print('press ctrl- to stop ' time sleep( leftwidth gapwidth while true display the tunnel segment rightwidth width gapwidth leftwidth print(('#leftwidth(gapwidth('#rightwidth)deep cave |
6,753 | check for ctrl- press during the brief pausetrytime sleep(pause_amountexcept keyboardinterruptsys exit(when ctrl- is pressedend the program adjust the left side widthdiceroll random randint( if diceroll = and leftwidth leftwidth leftwidth decrease left side width elif diceroll = and leftwidth gapwidth width leftwidth leftwidth increase left side width elsepass do nothingno change in left side width adjust the gap width(!try uncommenting out all of the following code#diceroll random randint( #if diceroll = and gapwidth gapwidth gapwidth decrease gap width #elif diceroll = and leftwidth gapwidth width gapwidth gapwidth increase gap width #elsepass do nothingno change in gap width 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 (gapwidthon line to (gapwidth) what happens if you change random randint( on line to random randint( ) what happens if you change random randint( on line to random randint( ) what error message do you get if you delete or comment out leftwidth on line what happens if you change width on line to width - what error message do you get if you change pause_amount on line to pause_amount - project # |
6,754 | diamonds this program features small algorithm for drawing ascii-art diamonds of various sizes it contains functions for drawing either an outline or filled-in-style diamond of the size you dictate these functions are good practice for beginnertry to understand the pattern behind the diamond drawings as they increase in size |
6,755 | when you run diamonds pythe output will look like thisdiamondsby al sweigart al@inventwithpython com /\/\/\///\\\/\/\///\///\\\\\//\\/\--snip-how it works helpful approach to creating this program yourself is to "drawdiamonds of several sizes in your editor first and then figure out the pattern they follow as the diamond gets bigger this technique will help you realize that each row of an outline diamond has four partsthe number of leading spacesthe exterior forward slashthe number of interior spacesand the exterior backslash filled diamonds have several interior forward slashes and backslashes rather than interior spaces cracking this pattern is how wrote diamonds py """diamondsby al sweigart al@inventwithpython com draws diamonds of various sizes view this code at project # |
6,756 | // //\ /////\\ //\////\\\ /////\\\\\\/// //\\\\//\\\// \\/\\/\\/ \\\\\\ tagstinybeginnerartistic"" def main() print('diamondsby al sweigart al@inventwithpython com' display diamonds of sizes through for diamondsize in range( ) displayoutlinediamond(diamondsize print(print newline displayfilleddiamond(diamondsize print(print newline def displayoutlinediamond(size) display the top half of the diamond for in range(size) print((size )end=''left side space print('/'end=''left side of diamond print(( )end=''interior of diamond print('\\'right side of diamond display the bottom half of the diamond for in range(size) print(iend=''left side space print('\\'end=''left side of diamond print(((size )end=''interior of diamond print('/'right side of diamond def displayfilleddiamond(size) display the top half of the diamond for in range(size) print((size )end=''left side space print('/( )end=''left half of diamond print('\\( )right half of diamond display the bottom half of the diamond for in range(size) print(iend=''left side space print('\\(size )end=''left side of diamond print('/(size )right side of diamond if this program was run (instead of imported)run the game if __name__ ='__main__' main(diamonds |
6,757 | experimental changes to it on your ownyou can also try to figure out how to do the followingcreate other shapestrianglesrectanglesand rhombuses output the shapes to text file instead of the screen 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 when you change print('\\'on line to print('@') what happens when you change print(( )end=''on line to print('@( )end='') what happens when you change range( on line to range( ) what happens when you delete or comment out for in range(size)on line or on line project # |
6,758 | at this math quiz program rolls two to six dice whose sides you must add up as quickly as possible but this program operates as more than just automated flash cardsit draws the faces of the dice to random places on the screen the ascii-art aspect adds fun twist while you practice arithmetic |
6,759 | when you run dicemath pythe output will look like thisdice mathby al sweigart al@inventwithpython com add up the sides of all the dice displayed on the screen you have seconds to answer as many as possible you get points for each correct answer and lose point for each incorrect answer press enter to begin + ++ +enter the sum --snip-+ ++ +how it works the dice on the screen are represented by dictionary stored in the canvas variable in pythontuples are similar to listsbut their contents cannot be changed the keys to this dictionary are (xytuples marking the position of die' top left cornerwhile the values are one of the "dice tuplesin all_dice you can see in lines to that each dice tuple contains list of stringswhich graphically represents one possible die faceand an integer of how many pips are on the die face the program uses this information to display the dice and calculate their sum total lines to render the data in the canvas dictionary on the screen in manner similar to how project "conway' game of life,renders cells on the screen """dice mathby al sweigart al@inventwithpython com flash card addition game where you sum the total on random dice rolls view this code at tagslargeartisticgamemath"" import randomtime set up the constants dice_width dice_height canvas_width project # |
6,760 | the duration is in seconds quiz_duration (!try changing this to or min_dice (!try changing this to or max_dice (!try changing this to (!try changing these to different numbers reward (!points awarded for correct answers penalty (!points removed for incorrect answers (!try setting penalty to negative number to give points for wrong answers the program hangs if all of the dice can' fit on the screen assert max_dice < (['++' '|' ' |' '|' '++'] (['++' ' |' '|' ' |' '++'] (['++' ' |' '|' ' |' '++'] (['++' ' |' ' |' ' |' '++'] (['++' ' |' ' |' ' |' '++'] (['++' ' |' '|' ' |' '++'] (['++' ' |' ' |'dice math |
6,761 | ' |' '++'] (['++' ' |' ' |' ' |' '++'] (['++' ' |' '|' ' |' '++'] all_dice [ ad bd ad bd ad print('''dice mathby al sweigart al@inventwithpython com add up the sides of all the dice displayed on the screen you have {seconds to answer as many as possible you get {points for each correct answer and lose {point for each incorrect answer ''format(quiz_durationrewardpenalty) input('press enter to begin ' keep track of how many answers were correct and incorrect correctanswers incorrectanswers starttime time time( while time time(starttime quiz_durationmain game loop come up with the dice to display sumanswer dicefaces [ for in range(random randint(min_dicemax_dice)) die random choice(all_dice die[ contains the list of strings of the die face dicefaces append(die[ ] die[ contains the integer number of pips on the face sumanswer +die[ contains (xytuples of the top-left corner of each die topleftdicecorners [ figure out where dice should go for in range(len(dicefaces)) while true find random place on the canvas to put the die left random randint( canvas_width dice_width top random randint( canvas_height dice_height get the xy coordinates for all four corners left #top + project # |
6,762 | dice_height ( + dice_width ( topleftx left toplefty top toprightx left dice_width toprighty top bottomleftx left bottomlefty top dice_height bottomrightx left dice_width bottomrighty top dice_height check if this die overlaps with previous dice overlaps false for prevdieleftprevdietop in topleftdicecornersprevdieright prevdieleft dice_width prevdiebottom prevdietop dice_height check each corner of this die to see if it is inside of the area the previous diefor cornerxcornery in ((topleftxtoplefty)(toprightxtoprighty)(bottomleftxbottomlefty)(bottomrightxbottomrighty))if (prevdieleft <cornerx prevdieright and prevdietop <cornery prevdiebottom)overlaps true if not overlapsit doesn' overlapso we can put it heretopleftdicecorners append((lefttop)break draw the dice on the canvaskeys are (xytuples of intsvalues the character at that position on the canvascanvas {loop over each diefor (dieleftdietopin enumerate(topleftdicecorners)loop over each character in the die' facedieface dicefaces[ifor dx in range(dice_width)for dy in range(dice_height)copy this character to the correct place on the canvascanvasx dieleft dx canvasy dietop dy note that in diefacea list of stringsthe and are swappedcanvas[(canvasxcanvasy)dieface[dy][dxdisplay the canvas on the screenfor cy in range(canvas_height)for cx in range(canvas_width)print(canvas get((cxcy)')end=''dice math |
6,763 | print(print newline let the player enter their answer response input('enter the sum'strip( if response isdecimal(and int(response=sumanswer correctanswers + else print('incorrectthe answer is'sumanswer time sleep( incorrectanswers + display the final score score (correctanswers reward(incorrectanswers penalty print('correct'correctanswers print('incorrect:'incorrectanswers print('score'scoreafter 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 followingredesign the ascii-art dice faces add dice faces with seveneightor nine pips 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 line to all_dice [ ] what happens if you change get((cxcy)'on line to get((cxcy)') what happens if you change correctanswers + on line to orrectanswers + what error message do you get if you delete or comment out correct answers on line project # |
6,764 | dice roller dungeons dragons and other tabletop role-playing games use special dice that can have or even sides these games also have specific notation for indicating which dice to roll for example means rolling three six-sided dicewhile + means rolling one ten-sided die and adding two-point bonus to the roll this program simulates this dice rollingin case you forgot to bring your own it can also simulate rolling dice that don' physically existsuch as -sided die |
6,765 | when you run diceroller pythe output will look like thisdice rollerby al sweigart al@inventwithpython com --snip- ( + ( + - ( - ( --snip-how it works most of the code in this program is dedicated to ensuring that the input the user entered is properly formatted the actual random dice rolls themselves are simple calls to random randint(this function has no biaseach integer in the range passed to it is equally likely to be returned this makes random randint(ideal for simulating dice rolls """dice rollerby al sweigart al@inventwithpython com simulates dice rolls using the dungeons dragons dice roll notation view this code at tagsshortsimulation"" import randomsys print('''dice rollerby al sweigart al@inventwithpython com enter what kind and how many dice to roll the format is the number of dicefollowed by " "followed by the number of sides the dice have you can also add plus or minus adjustment examples rolls three -sided dice + rolls one -sided dieand adds - rolls two -sided dieand subtracts quit quits the program ''' while truemain program loop try dicestr input(''the prompt to enter the dice string if dicestr upper(='quit' print('thanks for playing!' sys exit( project # |
6,766 | clean up the dice stringdicestr dicestr lower(replace('''find the "din the dice string inputdindex dicestr find(' 'if dindex =- raise exception('missing the "dcharacter 'get the number of dice (the " in " + ")numberofdice dicestr[:dindexif not numberofdice isdecimal()raise exception('missing the number of dice 'numberofdice int(numberofdicefind if there is plus or minus sign for modifiermodindex dicestr find('+'if modindex =- modindex dicestr find('-'find the number of sides (the " in " + ")if modindex =- numberofsides dicestr[dindex :elsenumberofsides dicestr[dindex modindexif not numberofsides isdecimal()raise exception('missing the number of sides 'numberofsides int(numberofsidesfind the modifier amount (the " in " + ")if modindex =- modamount elsemodamount int(dicestr[modindex :]if dicestr[modindex='-'change the modification amount to negativemodamount -modamount simulate the dice rollsrolls [for in range(numberofdice)rollresult random randint( numberofsidesrolls append(rollresultdisplay the totalprint('total:'sum(rollsmodamount'(each die:'end=''display the individual rollsfor iroll in enumerate(rolls)rolls[istr(rollprint('join(rolls)end=''display the modifier amountif modamount ! modsign dicestr[modindexdice roller |
6,767 | print('{}{}format(modsignabs(modamount))end=''print(')'except exception as exccatch any exceptions and display the message to the userprint('invalid input enter something like " or " + 'print('input was invalid becausestr(exc)continue go back to the dice string prompt 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 multiplication modifier to complement the addition and subtraction modifier add the ability to automatically remove the lowest die roll 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 rolls append(rollresulton line what happens if you change rolls append(rollresulton line to rolls append(-rollresult) what happens if you delete or comment out print('join(rolls)end=''on line what happens if instead of dice roll you enter nothing project # |
6,768 | ta this program displays digital clock with the current time rather than render numeric characters directlythe sevseg py module from project "sevensegment display module,generates the drawings for each digit this program is similar to project "countdown |
6,769 | when you run digitalclock pythe output will look like this__ __ |__|______ ______ ______ __ __|__ __|__press ctrl- to quit how it works the digital clock program looks similar to project "countdown not only do they both import the sevseg py modulebut they must split up the multiline strings returned by sevseg getsevsegstr(with the splitlines(method this allows us to put colon made of asterisks in between the digits for the hourminuteand second sections of the clock compare this code with the code in countdown to see how it is similar and how it is different """digital clockby al sweigart al@inventwithpython com displays digital clock of the current time with seven-segment display press ctrl- to stop more info at requires sevseg py to be in the same folder view this code at tagstinyartistic"" import systime import sevseg imports our sevseg py program try while truemain program loop clear the screen by printing several newlines print('\ get the current time from the computer' clock currenttime time localtime( so we use -hour clocknot hours str(currenttime tm_hour if hours =' ' hours ' -hour clocks show : not : minutes str(currenttime tm_min seconds str(currenttime tm_sec get the digit strings from the sevseg module hdigits sevseg getsevsegstr(hours htoprowhmiddlerowhbottomrow hdigits splitlines( mdigits sevseg getsevsegstr(minutes mtoprowmmiddlerowmbottomrow mdigits splitlines( sdigits sevseg getsevsegstr(seconds project # |
6,770 | stoprowsmiddlerowsbottomrow sdigits splitlines( display the digits print(htoprow mtoprow stoprow print(hmiddlerow mmiddlerow smiddlerow print(hbottomrow mbottomrow sbottomrow print( print('press ctrl- to quit ' keep looping until the second changes while true time sleep( if time localtime(tm_sec !currenttime tm_sec break except keyboardinterrupt print('digital clockby al sweigart al@inventwithpython com' sys exit(when ctrl- is pressedend the program exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change time sleep( on line to time sleep( )what happens if you change the on lines and to what happens if you delete or comment out print('\ on line what error message do you get if you delete or comment out import sevseg on line digital clock |
6,771 | ta this program mimics the "digital streamvisualization from the science fiction movie the matrix random beads of binary "rainstream up from the bottom of the screencreating coolhacker-like visualization (unfortunatelydue to the way text moves as the screen scrolls downit' not possible to make the streams fall downward without using module such as bext |
6,772 | when you run digitalstream pythe output will look like thisdigital stream screensaverby al sweigart al@inventwithpython com press ctrl- to quit --snip- how it works like project "deep cave,this program uses the scrolling caused by print(calls to create an animation each column is represented by an integer in the columns listcolumns[ is an integer for the leftmost columnc olumns[ is an integer for the column to the right of that oneand so on the program initially sets these integers to meaning it prints (an empty space stringinstead of stream in that column randomlyit changes each integer to value between min_stream_length and max_stream _length that integer decreases by each time line is printed as long as column' integer is greater than the program prints random or in that column this produces the "digital streameffect you see on the screen """digital streamby al sweigart al@inventwithpython com screensaver in the style of the matrix movie' visuals view this code at tagstinyartisticbeginnerscrolling"" import randomshutilsystime set up the constants min_stream_length (!try changing this to or max_stream_length (!try changing this to pause (!try changing this to or stream_chars [' '' '(!try changing this to other characters density can range from to density (!try changing this to or get the size of the terminal window width shutil get_terminal_size()[ digital stream |
6,773 | newline automaticallyso reduce the width by one width - print('digital streamby al sweigart al@inventwithpython com' print('press ctrl- to quit ' time sleep( try for each columnwhen the counter is no stream is shown otherwiseit acts as counter for how many times or should be displayed in that column columns [ width while true set up the counter for each column for in range(width) if columns[ = if random random(<density restart stream on this column columns[irandom randint(min_stream_length max_stream_length display an empty space or / character if columns[ print(random choice(stream_chars)end='' columns[ - else print('end='' print(print newline at the end of the row of columns sys stdout flush(make sure text appears on the screen time sleep(pause except keyboardinterrupt sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followinginclude characters besides just and include shapes besides linesincluding rectanglestrianglesand diamonds 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 print('end=''on line to print('end='') project # |
6,774 | pause - what happens if you change columns[ on line to columns[ what happens if you change columns[ on line to columns[ < what happens if you change columns[ - on line to columns[ + digital stream |
6,775 | ua at deoxyribonucleic acid is tiny molecule that exists in every cell of our bodies and contains the blueprint for how our bodies grow it looks like double helix ( sort of twisted ladderof pairs of nucleotide moleculesg uaninecytosineadenineand thymine these are represented by the letters gcaand dna is long moleculeit' microscopicbut if it were stretched outits billion base pairs would be meters longthis program is simple animation of dna |
6,776 | when you run dna pythe output will look like thisdna animationby al sweigart al@inventwithpython com press ctrl- to quit # - # --- #ta#ta#at#gc# --- # - ## - # --- #gc#gc#ta#at# --- # - ## - # --- #at--snip-how it works similar to project "deep cave,and project "digital stream,this program creates scrolling animation by printing strings from the rows list the at and cg pairs are inserted into each string with the format(string method """dnaby al sweigart al@inventwithpython com simple animation of dna double-helix press ctrl- to stop inspired by matoken view this code at tagsshortartisticscrollingscience"" import randomsystime pause (!try changing this to or these are the individual rows of the dna animation rows # <use this to measure the number of spaces ##'index has no { #{}-{}#' #{}---{}#'dna visualization |
6,777 | #{}{}#' #{}{}#' #{}{}#' #{}{}#' #{}---{}#' #{}-{}#' ##'index has no { #{}-{}#' #{}---{}#' #{}{}#' #{}{}#' #{}{}#' #{}{}#' #{}---{}#' #{}-{}#' # <use this to measure the number of spaces try print('dna animationby al sweigart al@inventwithpython com' print('press ctrl- to quit ' time sleep( rowindex while truemain program loop increment rowindex to draw next row rowindex rowindex if rowindex =len(rows) rowindex row indexes and don' have nucleotides if rowindex = or rowindex = print(rows[rowindex] continue select random nucleotide pairsguanine-cytosine and adenine-thymine randomselection random randint( if randomselection = leftnucleotiderightnucleotide ' '' elif randomselection = leftnucleotiderightnucleotide ' '' elif randomselection = leftnucleotiderightnucleotide ' '' elif randomselection = leftnucleotiderightnucleotide ' '' print the row print(rows[rowindexformat(leftnucleotiderightnucleotide) time sleep(pauseadd slight pause except keyboardinterrupt sys exit(when ctrl- is pressedend the program project # |
6,778 | 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 rowindex rowindex on line to rowindex rowindex what happens if you change random randint( on line to random randint( ) what error message do you get if you set pause on line to pause - dna visualization |
6,779 | ducklings this program creates scrolling field of ducklings each duckling has slight variationsthey can face left or right and have two different body sizesfour types of eyestwo types of mouthsand three positions for their wings this gives us different possible variationswhich the ducklings program produces endlessly |
6,780 | when you run ducklings pythe output will look like thisduckling screensaverby al sweigart al@inventwithpython com press ctrl- to quit ==" )="^ >''^^^>" =^^("(">"^>((^^^("^(``^^(^^(()^( "^--snip-how it works this program represents ducklings with duckling class the random features of each ducking are chosen in the __init__(method of this classwhile the various body parts of each duckling are returned by the getheadstr()getbodystr()and getfeetstr(methods """duckling screensaverby al sweigart al@inventwithpython com screensaver of many many ducklings >=^^(``(">"(" >^( (>( ^^^ view this code at tagslargeartisticobject-orientedscrolling"" import randomshutilsystime set up the constants pause (!try changing this to or density (!try changing this to anything from to duckling_width left 'left right 'right beady 'beady wide 'wide happy 'happy aloof 'aloof chubby 'chubby very_chubby 'very chubby open 'open closed 'closedducklings |
6,781 | down 'down up 'up head 'head body 'body feet 'feet get the size of the terminal window width shutil get_terminal_size()[ we can' print to the last column on windows without it adding newline automaticallyso reduce the width by one width - def main() print('duckling screensaverby al sweigart' print('press ctrl- to quit ' time sleep( ducklinglanes [none(width /duckling_width while truemain program loop for lanenumducklingobj in enumerate(ducklinglanes) see if we should create duckling in this lane if (ducklingobj =none and random random(<density) place duckling in this lane ducklingobj duckling( ducklinglanes[lanenumducklingobj if ducklingobj !none draw duckling if there is one in this lane print(ducklingobj getnextbodypart()end='' delete the duckling if we've finished drawing it if ducklingobj parttodisplaynext =none ducklinglanes[lanenumnone else draw five spaces since there is no duckling here print(duckling_widthend='' print(print newline sys stdout flush(make sure text appears on the screen time sleep(pause class duckling def __init__(self) """create new duckling with random body features "" self direction random choice([leftright] self body random choice([chubbyvery_chubby] self mouth random choice([openclosed] self wing random choice([outupdown] if self body =chubby chubby ducklings can only have beady eyes self eyes beady project # |
6,782 | elseself eyes random choice([beadywidehappyaloof]self parttodisplaynext head def getheadstr(self)"""returns the string of the duckling' head ""headstr 'if self direction =leftget the mouthif self mouth =openheadstr +'>elif self mouth =closedheadstr +'=get the eyesif self eyes =beady and self body =chubbyheadstr +'"elif self eyes =beady and self body =very_chubbyheadstr +'elif self eyes =wideheadstr +"''elif self eyes =happyheadstr +'^^elif self eyes =aloofheadstr +'``headstr +'get the back of the head if self direction =rightheadstr +(get the back of the head get the eyesif self eyes =beady and self body =chubbyheadstr +'"elif self eyes =beady and self body =very_chubbyheadstr +"elif self eyes =wideheadstr +"''elif self eyes =happyheadstr +'^^elif self eyes =aloofheadstr +'``get the mouthif self mouth =openheadstr +'<elif self mouth =closedheadstr +'=if self body =chubbyget an extra space so chubby ducklings are the same width as very chubby ducklings headstr +ducklings |
6,783 | project # return headstr def getbodystr(self)"""returns the string of the duckling' body ""bodystr '(get the left side of the body if self direction =leftget the interior body spaceif self body =chubbybodystr +elif self body =very_chubbybodystr +get the wingif self wing =outbodystr +'>elif self wing =upbodystr +'^elif self wing =downbodystr +'vif self direction =rightget the wingif self wing =outbodystr +'<elif self wing =upbodystr +'^elif self wing =downbodystr +'vget the interior body spaceif self body =chubbybodystr +elif self body =very_chubbybodystr +bodystr +')get the right side of the body if self body =chubbyget an extra space so chubby ducklings are the same width as very chubby ducklings bodystr +return bodystr def getfeetstr(self)"""returns the string of the duckling' feet ""if self body =chubbyreturn ^elif self body =very_chubbyreturn def getnextbodypart(self)"""calls the appropriate display method for the next body part that needs to be displayed sets parttodisplaynext to none when finished "" |
6,784 | if self parttodisplaynext =head self parttodisplaynext body return self getheadstr( elif self parttodisplaynext =body self parttodisplaynext feet return self getbodystr( elif self parttodisplaynext =feet self parttodisplaynext none return self getfeetstr( 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 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 random choice([leftright]on line to random choice([left]) what happens if you change self parttodisplaynext body on line to self parttodisplaynext none what happens if you change self parttodisplaynext feet on line to self parttodisplaynext body what happens if you change return self getheadstr(on line to return self getfeetstr()ducklings |
6,785 | tching dr aw er when you move pen point around the screen with the wasd keysthe etching drawer forms picture by tracing continuous linelike the etch sketch toy let your artistic side break out and see what images you can createthis program also lets you save your drawings to text file so you can print them out later plusyou can copy and paste the wasd movements of other drawings into this programlike the wasd commands for the hilbert curve fractal presented on lines to of the source code |
6,786 | when you run etchingdrawer pythe output will look like figure - figure - drawing made in the etching drawer program how it works like project "dice math,this program uses dictionary stored in variable named canvas to record the lines of the drawing the keys are (xytuples and the values are strings representing the line shape to draw at those xy coordinates on the screen full list of unicode characters you can use in your python programs is given in appendix line has function call to open(that passes an encoding='utf- argument the reasons are beyond the scope of this bookbut this is necessary for windows to write the line characters to text file """etching drawerby al sweigart al@inventwithpython com an art program that draws continuous line around the screen using the wasd keys inspired by etch sketch toys for exampleyou can draw hilbert curve fractal with sdwddsasdsaawassdsassdwdsdwwawdddsassdwdsdwwawdwwasaawdwawddsdw or an even larger hilbert curve fractal with ddsaassddwddsddwwaawddddsddwddddsaasddsaaaawaasssddwddddsaasddsaaaawa asaaaawddwwaasaawaassddsaassddwddddsaasddsaaaawaassddsaassddwddsddwwa awddddddsaassddwddsddwwaawddwwaasaaaawddwaawddddsddwddsddwddddsaasdds aaaawaassddsaassddwddsddwwaawddddddsaassddwddsddwwaawddwwaasaaaawddwa awddddsddwwaawddwwaasaawaassddsaaaawaasaaaawddwaawddddsddwwwaasaaaawd dwaawddddsddwddddsaassddwddsddwwaawdd etching drawer |
6,787 | view this code at tagslargeartistic"" import shutilsys set up the constants for line characters up_down_char chr( character is '| left_right_char chr( character is '- down_right_char chr( character is '+ down_left_char chr( character is '+ up_right_char chr( character is '+ up_left_char chr( character is '+ up_down_right_char chr( character is '+ up_down_left_char chr( character is '+ down_left_right_char chr( character is '+ up_left_right_char chr( character is '+ cross_char chr( character is '+ list of chr(codes is at get the size of the terminal window canvas_widthcanvas_height shutil get_terminal_size( we can' print to the last column on windows without it adding newline automaticallyso reduce the width by one canvas_width - leave room at the bottom few rows for the command info lines canvas_height - """the keys for canvas will be (xyinteger tuples for the coordinate and the value is set of letters wasd that tell what kind of line should be drawn "" canvas { cursorx cursory def getcanvasstring(canvasdatacxcy) """returns multiline string of the line drawn in canvasdata "" canvasstr ' """canvasdata is dictionary with (xytuple keys and values that are sets of ' '' '' 'and/or 'dstrings to show which directions the lines are drawn at each xy point "" for rownum in range(canvas_height) for columnnum in range(canvas_width) if columnnum =cx and rownum =cy canvasstr +'# continue add the line character for this point to canvasstr cell canvasdata get((columnnumrownum) if cell in (set([' '' '])set([' '])set([' '])) canvasstr +up_down_char elif cell in (set([' '' '])set([' '])set([' '])) canvasstr +left_right_char project # |
6,788 | elif cell =set([' '' ']) canvasstr +down_right_char elif cell =set([' '' ']) canvasstr +down_left_char elif cell =set([' '' ']) canvasstr +up_right_char elif cell =set([' '' ']) canvasstr +up_left_char elif cell =set([' '' '' ']) canvasstr +up_down_right_char elif cell =set([' '' '' ']) canvasstr +up_down_left_char elif cell =set([' '' '' ']) canvasstr +down_left_right_char elif cell =set([' '' '' ']) canvasstr +up_left_right_char elif cell =set([' '' '' '' ']) canvasstr +cross_char elif cell =none canvasstr + canvasstr +'\nadd newline at the end of each row return canvasstr moves [ while truemain program loop draw the lines based on the data in canvas print(getcanvasstring(canvascursorxcursory) print('wasd keys to moveh for helpc to clear ' to saveor quit ' response input(''upper( if response ='quit' print('thanks for playing!' sys exit(quit the program elif response =' ' print('enter wasand characters to move the cursor and' print('draw line behind it as it moves for exampleddd' print('draws line going right and sssdddwwwaaa draws box ' print( print('you can save your drawing to text file by entering ' input('press enter to return to the program ' continue elif response =' ' canvas {erase the canvas data moves append(' 'record this move elif response =' ' save the canvas string to text file try print('enter filename to save to:' filename input('' make sure the filename ends with txt if not filename endswith(txt')etching drawer |
6,789 | project # filename +txtwith open(filename' 'encoding='utf- 'as filefile write('join(moves'\ 'file write(getcanvasstring(canvasnonenone)exceptprint('errorcould not save file 'for command in responseif command not in (' '' '' '' ')continue ignore this letter and continue to the next one moves append(commandrecord this move the first line we add needs to form full lineif canvas ={}if command in (' '' ')make the first line horizontal onecanvas[(cursorxcursory)set([' '' ']elif command in (' '' ')make the first line vertical onecanvas[(cursorxcursory)set([' '' ']update and yif command ='wand cursory canvas[(cursorxcursory)add(commandcursory cursory elif command ='sand cursory canvas_height canvas[(cursorxcursory)add(commandcursory cursory elif command ='aand cursorx canvas[(cursorxcursory)add(commandcursorx cursorx elif command ='dand cursorx canvas_width canvas[(cursorxcursory)add(commandcursorx cursorx elseif the cursor doesn' move because it would have moved off the edge of the canvasthen don' change the set at canvas[(cursorxcursory)continue if there' no set for (cursorxcursory)add an empty setif (cursorxcursorynot in canvascanvas[(cursorxcursory)set(add the direction string to this xy point' setif command =' 'canvas[(cursorxcursory)add(' 'elif command =' 'canvas[(cursorxcursory)add(' 'elif command =' 'canvas[(cursorxcursory)add(' 'elif command =' 'canvas[(cursorxcursory)add(' ' |
6,790 | 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 response input(''upper(on line to response input('') what happens if you change canvasstr +'#on line to canvasstr +'@' what happens if you change canvasstr +on line to canvasstr +' what happens if you change moves [on line to moves list ('sdwddsasdsaawassdsas')etching drawer |
6,791 | fac de number' factors are any two other numbers thatwhen multiplied with each otherproduce the number for example so and are factors of also so and are also factors of thereforewe say that has four factors and if number only has two factors ( and itself)we call that prime number otherwisewe call it composite number use the factor finder to discover some new prime numbers(hintprime numbers always end with an odd number that isn' you can also have the computer calculate them with project "prime numbers the math for this program isn' too heavymaking it an ideal project for beginners |
6,792 | when you run factorfinder pythe output will look like thisfactor finderby al sweigart al@inventwithpython com --snip-enter number to factor (or "quitto quit) enter number to factor (or "quitto quit) enter number to factor (or "quitto quit) enter number to factor (or "quitto quit)quit how it works we can tell if number is factor of another number by checking if the second number evenly divides the first number for example is factor of because is this also gives us another of ' factors however is not factor of because the fractional remainder component tells us this equation did not divide evenly the mod operator will perform division and tell us if there' remainder evaluates to meaning there is no remainder and is factor of whereas evaluates to nonzero valuemeaning that it isn' factor the factor finder program uses this technique on line to determine which numbers are factors the math sqrt(function returns the square root of the number passed to it for examplemath sqrt( returns because times itself is making it the square root of """factor finderby al sweigart al@inventwithpython com finds all the factors of number view this code at tagstinybeginnermath"" import mathsys print('''factor finderby al sweigart al@inventwithpython com number' factors are two numbers thatwhen multiplied with each factor finder |
6,793 | factors of so and are also factors of we say that has four factors and if number only has two factors ( and itself)we call that prime number otherwisewe call it composite number can you discover some prime numbers ''' while truemain program loop print('enter positive whole number to factor (or quit):' response input('' if response upper(='quit' sys exit( if not (response isdecimal(and int(response ) continue number int(response factors [ find the factors of number for in range( int(math sqrt(number) ) if number = if there' no remainderit is factor factors append( factors append(number / convert to set to get rid of duplicate factors factors list(set(factors) factors sort( display the results for ifactor in enumerate(factors) factors[istr(factor print('join(factors)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 factors append(ion line what happens if you delete or comment out factors list(set(factors)on line (hintenter square number such as or or what happens if you delete or comment out factors sort(on line project # |
6,794 | factors '' what happens if you change factors [on line to factors [- ] what error message do you get if you change factors [on line to factors ['hello']factor finder |
6,795 | fa aw this program tests your reaction speedpress enter as soon as you see the word draw but carefulthough press it before draw appearsand you lose are you the fastest keyboard in the west |
6,796 | when you run fastdraw pythe output will look like thisfast drawby al sweigart al@inventwithpython com time to test your reflexes and see if you are the fastest draw in the westwhen you see "draw"you have seconds to press enter but you lose if you press enter before "drawappears press enter to begin it is high noon drawyou took seconds to draw too slowenter quit to stopor press enter to play again quit thanks for playinghow it works the input(function pauses the program while waiting for the user to enter string this simple behavior means that we can' create real-time games with just input(howeveryour programs will buffer keyboard inputmeaning that if you pressed the caand keys before input(is calledthose characters will be savedand they'll appear immediately once input(executes by recording the time just before the input(call on line and the time just after the input(call on line we can determine how long the player took to press enter howeverif they pressed enter before input(was calledthe buffered enter press causes input(to return immediately (usually in about millisecondsthis is why line checks if the time was less than secondsor millisecondsto determine that the player pressed enter too soon """fast drawby al sweigart al@inventwithpython com test your reflexes to see if you're the fastest draw in the west view this code at tagstinybeginnergame"" import randomsystime print('fast drawby al sweigart al@inventwithpython com' print( print('time to test your reflexes and see if you are the fastest' print('draw in the west!' print('when you see "draw"you have seconds to press enter ' print('but you lose if you press enter before "drawappears ' print( input('press enter to begin 'fast draw |
6,797 | while true print( print('it is high noon ' time sleep(random randint( print('draw!' drawtime time time( input(this function call doesn' return until enter is pressed timeelapsed time time(drawtime if timeelapsed if the player pressed enter before drawappearedthe input( call returns almost instantly print('you drew before "drawappearedyou lose ' elif timeelapsed timeelapsed round(timeelapsed print('you took'timeelapsed'seconds to draw too slow!' else timeelapsed round(timeelapsed print('you took'timeelapsed'seconds to draw ' print('you are the fastest draw in the westyou win!' print('enter quit to stopor press enter to play again ' response input(''upper( if response ='quit' print('thanks for playing!' sys exit(exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change drawtime time time(on line to drawtime what happens if you change timeelapsed on line to timeelapsed what happens if you change time time(drawtime on line to time time(drawtime what happens if you delete or comment out input('press enter to begin 'on line project # |
6,798 | fibonacci the fibonacci sequence is famous mathematical pattern credited to italian mathematician fibonacci in the th century (though others had discovered it even earlierthe sequence begins with and and the next number is always the sum of the previous two numbers the sequence continues forever the fibonacci sequence has applications in music compositionstock market predictionthe pattern of florets in the head of sunflowersand many other areas this program lets you calculate the sequence as high as you are willing to go more information about the fibonacci sequence can be found at |
6,799 | when you run fibonacci pythe output will look like thisfibonacci sequenceby al sweigart al@inventwithpython com --snip-enter the nth fibonacci number you wish to calculate (such as )or quit to quit how it works because fibonacci numbers quickly become very largelines to check if the user has entered number that' , or larger and displays warning that it may take some time for the output to finish displaying on the screen while your programs can quickly do millions of calculations almost instantlyprinting text to the screen is relatively slow and could take several seconds the warning in our program reminds the user they can always terminate the program by pressing ctrl- """fibonacci sequenceby al sweigart al@inventwithpython com calculates numbers of the fibonacci sequence view this code at tagsshortmath"" import sys print('''fibonacci sequenceby al sweigart al@inventwithpython com the fibonacci sequence begins with and and the next number is the sum of the previous two numbers the sequence continues forever ''' while truemain program loop while truekeep asking until the user enters valid input print('enter the nth fibonacci number you wish to' print('calculate (such as )or quit to quit:' response input(''upper( if response ='quit' print('thanks for playing!' sys exit( if response isdecimal(and int(response! nth int(response project # |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.