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...
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 fi...
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...
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 th...
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!' m...
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(card...
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 mov...
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 tr...
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 a...
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 remembe...
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 ...
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...
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_...
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 exi...
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 t...
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 ...
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 ex...
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...
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 y...
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 vqp...
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 di...
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 fa...
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 +++++++| | | | | | +++++++ +++++++ | | | | | | +++++++| | | | | | | +++++++...
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 s...
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 her...
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 ...
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 box...
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 ent...
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('''carro...
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 'te...
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 |___||____| |// ++ {{ bo...
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 explori...
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 especiall...
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 t...
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...
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 ...
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 pro...
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 psychi...
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(numbe...
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(posses...
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 ...
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...
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@inv...
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=t...
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 ...
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 ...
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...
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 ...
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 num...
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 as...
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...
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 simi...
6,752
when you run deepcave pythe output will look like thisdeep caveby al sweigart al@inventwithpython com press ctrl- to stop ######################################################################################################################################################################################################...
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 l...
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 i...
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 diamo...
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(...
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...
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 t...
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 poin...
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 i...
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 ...
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('co...
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 prog...
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 t...
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 'numbero...
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 t...
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 getsevseg...
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 bre...
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...
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 column...
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 whi...
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...
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 b...
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 progr...
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...
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 __ini...
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 ...
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...
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 ...
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 __n...
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 pl...
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...
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_rig...
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 eli...
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 mo...
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 yo...
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 us...
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 ...
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(''...
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 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 befo...
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 ...
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 l...