id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
10,800 | def readlevelsfile(filename) assert os path exists(filename)'cannot find the level file% (filenamethe os path exists(function will return true if the file specified by the string passed to the function exists if it does not existos path exists(returns false mapfile open(filename' 'each level must end with blank line co... |
10,801 | the for loop on line will go through each line that was read from the level file one line at time the line number will be stored in linenum and the string of text for the line will be stored in line any newline characters at the end of the string will be stripped off if ';in lineignore the linesthey're comments in the ... |
10,802 | when it finds new longest string after this loop finishes executingthe maxwidth variable will be set to the length of the longest string in maptextlines add spaces to the ends of the shorter rows this ensures the map will be rectangular for in range(len(maptextlines))maptextlines[ +(maxwidth len(maptextlines[ ])the for... |
10,803 | if mapobj[ ][yin ('$''*')'$is star stars append((xy)after creating the map objectthe nested for loops on lines and will go through each space to find the xy coordinates three things the player' starting position this will be stored in the startx and starty variableswhich will then be stored in the game state object lat... |
10,804 | 'stars'starslevelobj {'width'maxwidth'height'len(mapobj)'mapobj'mapobj'goals'goals'startstate'gamestateobjlevels append(levelobjfinallythese objects are stored in the game state objectwhich itself is stored in the level object the level object is added to list of level objects on line it is this levels list that will b... |
10,805 | when you run this programthe function gets defined when the def statement on line executes the next line of code that is executed is line kwhich calls passfortytwowhenyoucallthisfunction(and passes (gasp! as resultthe function calls itself on line and passes we call this call the recursive call this is what our program... |
10,806 | def funky()funky(funky(if you run this programyou'll get large amount of output which looks like thisfile " :\test py"line in funky funky(file " :\test py"line in funky funky(file " :\test py"line in funky funky(file " :\test py"line in funky funky(file " :\test py"line in funky funky(runtimeerrormaximum recursion dept... |
10,807 | file " :\test py"line in eggs spam(file " :\test py"line in spam eggs(file " :\test py"line in eggs spam(file " :\test py"line in spam eggs(runtimeerrormaximum recursion depth exceeded preventing stack overflows with base case in order to prevent stack overflow bugsyou must have base case where the function stops make ... |
10,808 | fizz(param file " :\rectest py"line in fizz print(paramruntimeerrormaximum recursion depth exceeded recursive calls and base cases will be used to perform the flood fill algorithmwhich is described next the flood fill algorithm the flood fill algorithm is used in star pusher to change all of the floor tiles inside the ... |
10,809 | to better understand how the floodfill(function workshere is version that does not use recursive callsbut instead uses list of xy coordinates to keep track of which spaces on the map should be checked and possibly changed to newcharacter def floodfill(mapobjxyoldcharacternewcharacter)spacestocheck [if mapobj[ ][ =oldch... |
10,810 | on is created on line to begin withthe entire surface object is painted to the background color on line draw the tile sprites onto this surface for in range(len(mapobj)) for in range(len(mapobj[ ])) spacerect pygame rect(( tilewidthy (tileheight tilefloorheight)tilewidthtileheight)the set of nested for loops on line an... |
10,811 | coordinate (which is done on line before the star is drawnthe code should first check if there is also goal at this locationin which casethe --covered goal|tile should be drawn first elif (xyin goalsdraw goal without star on it mapsurf blit(imagesdict['uncovered goal']spacerectif there is goal at this xy coordinate on ... |
10,812 | work here because gamestateobj['stars'is list of those same tuples of xy coordinatesthe first time the code finds goal with no star at the same positionthe function returns false if it gets through all of the goals and finds star on each of themislevelfinished(returns true def terminate() pygame quit( sys exit(this ter... |
10,813 | four extra games included in this is the source code for four extra games unfortunatelyonly the source code (including commentsis in this without any detailed explanation of the code by nowyou can play these games and figure out how the code works by looking at the source code and comments the games areflippy an --othe... |
10,814 | flippyan "othelloclone othelloalso known by the generic name reversihas an board with tiles that are black on one side and white on the other the starting board looks like figure - each player takes turn placing down new tile of their color any of the opponent' tiles that are between the new tile and the other tiles of... |
10,815 | the black tile at is in between the new white tile and the existing white tile at that black tile is flipped over and becomes new white tilemaking the board look like figure - black makes similar move nextplacing black tile on which flips the white tile at this results in board that looks like figure - white' move will... |
10,816 | white' second move at will flip two of black' tiles the board after white' second move as you can seeeach player can quickly grab majority of the tiles on the board in just one or two moves players must always make move that captures at least one tile the game ends when player either cannot make moveor the board is com... |
10,817 | by al sweigart al@inventwithpython com released under "simplified bsdlicense based on the "reversi pycode that originally appeared in "invent your own computer games with python" import randomsyspygametimecopy from pygame locals import fps frames per second to update the screen windowwidth width of the program' windowi... |
10,818 | mainclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) pygame display set_caption('flippy' font pygame font font('freesansbold ttf' bigfont pygame font font('freesansbold ttf' set up the background image boardimage pygame image load('flippyboard png' use smoothscale(to stretch the bo... |
10,819 | hintsrect hintssurf get_rect( hintsrect topright (windowwidth while truemain game loop keep looping for player and computer' turns if turn ='player' player' turn if getvalidmoves(mainboardplayertile=[] if it' the player' turn but they can' movethen end the game break movexy none while movexy =none keep looping until th... |
10,820 | displaysurf blit(hintssurfhintsrectmainclock tick(fpspygame display update(make the move and end the turn makemove(mainboardplayertilemovexy[ ]movexy[ ]trueif getvalidmoves(mainboardcomputertile![]only set for the computer' turn if it can make move turn 'computerelsecomputer' turnif getvalidmoves(mainboardcomputertile=... |
10,821 | elif scores[playertilescores[computertile] text 'you lost the computer beat you by % points (scores[computertilescores[playertile] else text 'the game was tie! textsurf font render(texttruetextcolortextbgcolor textrect textsurf get_rect( textrect center (int(windowwidth )int(windowheight ) displaysurf blit(textsurftext... |
10,822 | def translateboardtopixelcoord(xy) return xmargin spacesize int(spacesize )ymargin spacesize int(spacesize def animatetilechange(tilestofliptilecoloradditionaltile) draw the additional tile that was just laid down (otherwise we' have to completely redraw the board the board info if tilecolor =white_tile additionaltilec... |
10,823 | draw the horizontal lines startx ( spacesizexmargin starty ymargin endx ( spacesizexmargin endy ymargin (boardheight spacesize pygame draw line(displaysurfgridlinecolor(startxstarty)(endxendy) for in range(boardheight ) draw the vertical lines startx xmargin starty ( spacesizeymargin endx xmargin (boardwidth spacesize ... |
10,824 | draws scores and whose turn it is at the bottom of the screen scores getscoreofboard(board scoresurf font render("player score% computer score% % ' turn(str(scores[playertile])str(scores[computertile])turn title())truetextcolor scorerect scoresurf get_rect( scorerect bottomleft ( windowheight displaysurf blit(scoresurf... |
10,825 | tilestoflip [ check each of the eight directions for xdirectionydirection in [[ ][ ][ ][ - ][ ][- - ][- ][- ]] xy xstartystart +xdirection +ydirection if isonboard(xyand board[ ][ =othertile the piece belongs to the other player next to our piece +xdirection +ydirection if not isonboard(xy) continue while board[ ][ =ot... |
10,826 | for xy in getvalidmoves(dupeboardtile) dupeboard[ ][yhint_tile return dupeboard def getvalidmoves(boardtile) returns list of ( ,ytuples of all valid moves validmoves [ for in range(boardwidth) for in range(boardheight) if isvalidmove(boardtilexy!false validmoves append((xy) return validmoves def getscoreofboard(board) ... |
10,827 | orect osurf get_rect( orect center (int(windowwidth int(windowheight while true keep looping until the player has clicked on color checkforquit( for event in pygame event get()event handling loop if event type =mousebuttonup mousexmousey event pos if xrect collidepoint(mousexmousey) return [white_tileblack_tile elif or... |
10,828 | def getcomputermove(boardcomputertile) given board and the computer' tiledetermine where to move and return that move as [xylist possiblemoves getvalidmoves(boardcomputertile randomize the order of the possible moves random shuffle(possiblemoves always go for corner if available for xy in possiblemoves if isoncorner(xy... |
10,829 | ink spilla "flood itclone the game --flood it|begins with board filled with colored tiles on each turn the player chooses new color to paint the top left tile and any tiles adjacent to it of that same color this game makes use of the flood fill algorithm (described in the star pusher the goal of the game is to turn the... |
10,830 | mediumboardsize largeboardsize smallmaxlife number of turns mediummaxlife largemaxlife fps windowwidth windowheight boxsize mediumboxsize palettegapsize palettesize easy arbitrary but unique value medium arbitrary but unique value hard arbitrary but unique value difficulty medium game starts in "mediummode maxlife medi... |
10,831 | (( )( )( )( )( )( )( )) for in range(len(colorschemes)) assert len(colorschemes[ ]= 'color scheme % does not have exactly colors ( bgcolor colorschemes[ ][ palettecolors colorschemes[ ][ : def main() global fpsclockdisplaysurflogoimagespotimagesettingsimagesettingsbuttonimageresetbuttonimage pygame init( fpsclock pygam... |
10,832 | if pygame rect(windowwidth settingsbuttonimage get_width() windowheight settingsbuttonimage get_height() settingsbuttonimage get_width() settingsbuttonimage get_height()collidepoint(mousexmousey) resetgame showsettingsscreen(clicked on settings button elif pygame rect(windowwidth resetbuttonimage get_width() windowheig... |
10,833 | pygame time wait( pause so the player can suffer in their defeat if resetgame start new game mainboard generaterandomboard(boardwidthboardheightdifficulty life maxlife lastpaletteclicked none pygame display update( fpsclock tick(fps def checkforquit() terminates the program if there are any quit or escape key events fo... |
10,834 | screenneedsredraw true while true if screenneedsredraw displaysurf fill(bgcolor displaysurf blit(settingsimage( , ) place the ink spot marker next to the selected difficulty if difficulty =easy displaysurf blit(spotimage( ) if difficulty =medium displaysurf blit(spotimage( ) if difficulty =hard displaysurf blit(spotima... |
10,835 | elif pygame rect( collidepoint(mousexmousey) difficulty medium elif pygame rect( collidepoint(mousexmousey) difficulty hard check for clicks on the size buttons elif pygame rect( collidepoint(mousexmousey) small board size setting boxsize smallboxsize boardwidth smallboardsize boardheight smallboardsize maxlife smallma... |
10,836 | def drawcolorschemeboxes(xyschemenum) draws the color scheme boxes that appear on the "settingsscreen for boxy in range( ) for boxx in range( ) pygame draw rect(displaysurfcolorschemes[schemenum][ boxy boxx ]( mediumboxsize boxxy mediumboxsize boxymediumboxsizemediumboxsize) if palettecolors =colorschemes[schemenum][ :... |
10,837 | creates board data structure with random colors for each box board [for in range(width)column [for in range(height)column append(random randint( len(palettecolors )board append(columnmake board easier by setting some boxes to same color as neighbor determine how many boxes to change if difficulty =easyif boxsize =small... |
10,838 | def drawlogoandbuttons() draw the ink spill logo and settings and reset buttons displaysurf blit(logoimage(windowwidth logoimage get_width() ) displaysurf blit(settingsbuttonimage(windowwidth settingsbuttonimage get_width()windowheight settingsbuttonimage get_height()) displaysurf blit(resetbuttonimage(windowwidth rese... |
10,839 | def drawlifemeter(currentlife) lifeboxsize int((windowheight maxlife draw background color of life meter pygame draw rect(displaysurfbgcolor( (maxlife lifeboxsize)) for in range(maxlife) if currentlife >(maxlife )draw solid red box pygame draw rect(displaysurfred( ( lifeboxsize) lifeboxsize) pygame draw rect(displaysur... |
10,840 | if floodfill(boardoldcolornewcolorxy on box to up if boardheight floodfill(boardoldcolornewcolorxy on box to down def lefttoppixelcoordofbox(boxxboxy) returns the and of the left-topmost pixel of the xth yth box xmargin int((windowwidth (boardwidth boxsize) ymargin int((windowheight (boardheight boxsize) return (boxx b... |
10,841 | four-in- -rowa "connect fourclone the game --connect four|has board where the players take turns dropping tokens from the top of the board the tokens will fall from the top of each column and come to rest on the bottom of the board or on top of the topmost token in that column player wins when four of their tokens line... |
10,842 | the image files that flippy uses can be downloaded from four-in- -row ( connect four clone by al sweigart al@inventwithpython com released under "simplified bsdlicense import randomcopysyspygame from pygame locals import boardwidth how many spaces wide the board is boardheight how many spaces tall the board is assert b... |
10,843 | pygame display set_caption('four in row' redpilerect pygame rect(int(spacesize )windowheight int( spacesize )spacesizespacesize blackpilerect pygame rect(windowwidth int( spacesize )windowheight int( spacesize )spacesizespacesize redtokenimg pygame image load(' row_red png' redtokenimg pygame transform smoothscale(redt... |
10,844 | showhelp false set up blank board data structure mainboard getnewboard( while truemain game loop if turn =human human player' turn gethumanmove(mainboardshowhelp if showhelp turn off help arrow after the first move showhelp false if iswinner(mainboardred) winnerimg humanwinnerimg break turn computer switch to other pla... |
10,845 | def makemove(boardplayercolumn) lowest getlowestemptyspace(boardcolumn if lowest !- board[column][lowestplayer def drawboard(boardextratoken=none) displaysurf fill(bgcolor draw tokens spacerect pygame rect( spacesizespacesize for in range(boardwidth) for in range(boardheight) spacerect topleft (xmargin ( spacesize)ymar... |
10,846 | def gethumanmove(boardisfirstmove) draggingtoken false tokenxtokeny nonenone while true for event in pygame event get()event handling loop if event type =quit pygame quit( sys exit( elif event type =mousebuttondown and not draggingtoken and redpilerect collidepoint(event pos) start of dragging on red token pile draggin... |
10,847 | def animatedroppingtoken(boardcolumncolor) xmargin column spacesize ymargin spacesize dropspeed lowestemptyspace getlowestemptyspace(boardcolumn while true +int(dropspeed dropspeed + if int(( ymarginspacesize>lowestemptyspace return drawboard(board{' ': ' ': 'color':color} pygame display update( fpsclock tick( def anim... |
10,848 | for in range(boardwidth) if potentialmoves[ibestmovefitness and isvalidmove(boardi) bestmovefitness potentialmoves[ find all potential moves that have this best fitness bestmoves [ for in range(len(potentialmoves)) if potentialmoves[ =bestmovefitness and isvalidmove(boardi) bestmoves append( return random choice(bestmo... |
10,849 | else do the recursive call to getpotentialmoves( results getpotentialmoves(dupeboard tilelookahead potentialmoves[firstmove+(sum(resultsboardwidthboardwidth return potentialmoves def getlowestemptyspace(boardcolumn) return the row number of the lowest empty row in the given column for in range(boardheight- - - ) if boa... |
10,850 | return true check diagonal spaces for in range(boardwidth ) for in range( boardheight) if board[ ][ =tile and board[ + ][ - =tile and board[ + ][ - =tile and board[ + ][ - =tile return true check diagonal spaces for in range(boardwidth ) for in range(boardheight ) if board[ ][ =tile and board[ + ][ + =tile and board[ +... |
10,851 | gemgema "bejeweledclone --bejeweled|is game where gems fall to fill up board the player can swap any two adjacent gems to try to match three gems in row (vertically or horizontallybut not diagonallythe matched gems then disappearmaking way for new gems to fall from the top matching more than three gemsor causing chain ... |
10,852 | import randomtimepygamesyscopy from pygame locals import fps frames per second to update the screen windowwidth width of the program' windowin pixels windowheight height in pixels boardwidth how many columns in the board boardheight how many rows in the board gemimagesize width height of each space in pixels numgemimag... |
10,853 | right 'right empty_space - an arbitrarynonpositive value rowaboveboard 'row above boardan arbitrarynoninteger value def main() global fpsclockdisplaysurfgemimagesgamesoundsbasicfontboardrects initial set up pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) pygame dis... |
10,854 | def rungame() plays through single game when the game is overthis function returns initialize the board gameboard getblankboard( score fillboardandanimate(gameboard[]scoredrop the initial gems initialize variables for the start of new game firstselectedgem none lastmousedownx none lastmousedowny none gameisover false l... |
10,855 | elif event type =mousebuttondown this is the start of mouse click or mouse drag lastmousedownxlastmousedowny event pos if clickedspace and not firstselectedgem this was the first gem clicked on firstselectedgem clickedspace elif clickedspace and firstselectedgem two gems have been clicked on and selected swap the gems ... |
10,856 | points is list of dicts that tells fillboardandanimate( where on the screen to display text to show how many points the player got points is list because if the player gets multiple matchesthen multiple points text should appear points [ for gemset in matchedgems scoreadd +( (len(gemset for gem in gemset gameboard[gem[... |
10,857 | score - lastscorededuction time time( drawscore(score pygame display update( fpsclock tick(fps def getswappinggems(boardfirstxysecondxy) if the gems at the (xycoordinates of the two gems are adjacent then their 'directionkeys are set to the appropriate direction value to be swapped with each other otherwise(nonenoneis ... |
10,858 | return board def canmakemove(board) return true if the board is in state where matching move can be made on it otherwise return false the patterns in oneoffpatterns represent gems that are configured in way where it only takes one move to make triplet oneoffpatterns ((( , )( , )( , )) (( , )( , )( , )) (( , )( , )( , )... |
10,859 | return true return true the first time you find pattern return false def drawmovinggem(gemprogress) draw gem sliding in the direction that its 'directionkey indicates the progress parameter is number from (just startingto (slide complete movex movey progress * if gem['direction'=up movey -int(progress gemimagesize elif... |
10,860 | if boardwidth or >boardheight return none else return board[ ][ def getdropslots(board) creates "drop slotfor each column and fills the slot with number of gems that that column is lacking this function assumes that the gems have been gravity dropped already boardcopy copy deepcopy(board pulldownallgems(boardcopy drops... |
10,861 | for in range(boardwidth) for in range(boardheight) look for horizontal matches if getgemat(boardcopyxy=getgemat(boardcopyx =getgemat(boardcopyx yand getgemat(boardcopyxy!empty_space targetgem boardcopy[ ][ offset removeset [ while getgemat(boardcopyx offsety=targetgem keep checkingin case there' more than gems in row r... |
10,862 | droppinggems append{'imagenum'boardcopy[ ][ ]' ' ' ' 'direction'down boardcopy[ ][yempty_space return droppinggems def animatemovinggems(boardgemspointstextscore) pointstext is dictionary with keys ' '' 'and 'points progress progress at represents beginning means finished while progress animation loop displaysurf fill(... |
10,863 | board[gem[' ']][ gem['imagenum'move to top row def fillboardandanimate(boardpointsscore) dropslots getdropslots(board while dropslots ![[]boardwidth do the dropping animation as long as there are more gems to drop movinggems getdroppinggems(board for in range(len(dropslots)) if len(dropslots[ ]! cause the lowest gem in... |
10,864 | def getboardcopyminusgems(boardgems) creates and returns copy of the passed board data structure with the gems in the "gemslist removed from it gems is list of dictswith keys xydirectionimagenum boardcopy copy deepcopy(board remove some of the gems from this board data structure copy for gem in gems if gem[' '!rowabove... |
10,865 | code for these programs and additional information this site also has the image and sound files used in the pygame programs games with python||which covers basic python programming you can look up if you need to learn about something specific the programs in this bookstep by step games al@inventwithpython com my email ... |
10,866 | glossary alpha value the amount of transparency for color in pygamealpha values range from (completely transparentto (completely opaqueanti-aliasing technique for making shapes look smoother and less blocky by adding fuzzy colors to their edges anti-aliased drawings look smooth aliased drawings look blocky attributes v... |
10,867 | venture of iit bombay vjti alumni it provides very high-level dynamic data types and supports dynamic type checking it supports automatic garbage collection it can be easily integrated with cc++comactivexcorbaand java |
10,868 | venture of iit bombay vjti alumni python environment setup python is available on wide variety of platforms including linux and mac os let' understand how to set up our python environment local environment setup open terminal window and type "pythonto find out if it is already installed and which version is installed u... |
10,869 | venture of iit bombay vjti alumni vms/openvms qnx vxworks psion python has also been ported to the java and net virtual machines installing python python distribution is available for wide variety of platforms you need to download only the binary code applicable for your platform and install python if the binary code f... |
10,870 | venture of iit bombay vjti alumni run /configure script make make install this installs python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonxx where xx is the version of python windows installation here are the steps to install python on windows machine open web browser and go to follow... |
10,871 | venture of iit bombay vjti alumni macintosh installation recent macs come with python installedbut it may be several years out of date see version along with extra tools to support development on the mac for older mac os' before mac os (released in )macpython is available jack jansen maintains it and you can have full ... |
10,872 | venture of iit bombay vjti alumni setting path at unix/linux to add the python directory to the path for particular session in unix in the csh shell type setenv path "$path:/usr/local/bin/pythonand press enter in the bash shell (linuxtype export ath="$path:/usr/local/bin/pythonand press enter in the sh or ksh shell typ... |
10,873 | venture of iit bombay vjti alumni pythonpath it has role similar to path this variable tells the python interpreter where to locate the module files imported into program it should include the python source library directory and the directories containing python source code pythonpath is sometimes preset by the python ... |
10,874 | venture of iit bombay vjti alumni it is an alternative module search path it is usually embedded in the pythonstartup or pythonpath directories to make switching module libraries easy running python there are three different ways to start python interactive interpreter you can start python from unixdosor any other syst... |
10,875 | venture of iit bombay vjti alumni sr no option description - it provides debug output - it generates optimized bytecode (resulting in pyo files - do not run import site to look for python paths on startup - verbose output (detailed trace on import statements - disable class-based built-in exceptions (just use strings)o... |
10,876 | venture of iit bombay vjti alumni - cmd run python script sent in as cmd string file run python script from given file script from the command-line python script can be executed at command line by invoking the interpreter on your applicationas in the following $python script py unix/linux or pythonscript py unix/linux ... |
10,877 | venture of iit bombay vjti alumni note be sure the file permission mode allows execution integrated development environment you can run python from graphical user interface (guienvironment as wellif you have gui application on your system that supports python unix idle is the very first unix ide for python windows pyth... |
10,878 | venture of iit bombay vjti alumni python basic syntax the python language has many similarities to perlcand java howeverthere are some definite differences between the languages first python program let us execute programs in different modes of programming interactive mode programming invoking the interpreter without p... |
10,879 | venture of iit bombay vjti alumni type the following text at the python prompt and press the enter print "hellopython!if you are running new version of pythonthen you would need to use print statement with parenthesis as in print ("hellopython!")however in python version this produces the following result hellopythonsc... |
10,880 | venture of iit bombay vjti alumni we assume that you have python interpreter set in path variable nowtry to run this program as follows python test py this produces the following result hellopythonlet us try another way to execute python script here is the modified test py file #!/usr/bin/python print "hellopython!we a... |
10,881 | venture of iit bombay vjti alumni hellopythonpython identifiers python identifier is name used to identify variablefunctionclassmodule or other object an identifier starts with letter to or to or an underscore (_followed by zero or more lettersunderscores and digits ( to python does not allow punctuation characters suc... |
10,882 | venture of iit bombay vjti alumni reserved words the following list shows the python keywords these are reserved words and you cannot use them as constant or variable or any other identifier names all the python keywords contain lowercase letters only and exec not assert finally or break for pass class from print conti... |
10,883 | venture of iit bombay vjti alumni del import try elif in while else is with except lambda yield lines and indentation python provides no braces to indicate blocks of code for class and function definitions or flow control blocks of code are denoted by line indentationwhich is rigidly enforced the number of spaces in th... |
10,884 | venture of iit bombay vjti alumni print "falsehoweverthe following block generates an error if trueprint "answerprint "trueelseprint "answerprint "falsethusin python all the continuous lines indented with same number of spaces would form block the following example has various statement blocks note do not try to unders... |
10,885 | venture of iit bombay vjti alumni tryopen file stream file open(file_name" "except ioerrorprint "there was an error writing to"file_name sys exit(print "enter '"file_finishprint "when finishedwhile file_text !file_finishfile_text raw_input("enter text"if file_text =file_finishclose the file file close break |
10,886 | venture of iit bombay vjti alumni file write(file_textfile write("\ "file close(file_name raw_input("enter filename"if len(file_name= print "next time please enter somethingsys exit(tryfile open(file_name" "except ioerrorprint "there was an error reading filesys exit(file_text file read(file close( |
10,887 | venture of iit bombay vjti alumni print file_text multi-line statements statements in python typically end with new line python doeshoweverallow the use of the line continuation character (\to denote that the line should continue for example total item_one item_two item_three statements contained within the []{}or (bra... |
10,888 | venture of iit bombay vjti alumni word 'wordsentence "this is sentence paragraph """this is paragraph it is made up of multiple lines and sentences ""comments in python hash sign (#that is not inside string literal begins comment all characters after the and up to the end of the physical line are part of the comment an... |
10,889 | venture of iit bombay vjti alumni you can comment multiple lines as follows this is comment this is commenttoo this is commenttoo said that already using blank lines line containing only whitespacepossibly with commentis known as blank line and python totally ignores it in an interactive interpreter sessionyou must ent... |
10,890 | venture of iit bombay vjti alumni here"\ \nis used to create two new lines before displaying the actual line once the user presses the keythe program ends this is nice trick to keep console window open until the user is done with an application multiple statements on single line the semicolon allows multiple statements... |
10,891 | venture of iit bombay vjti alumni suite else suite command line arguments many programs can be run to provide you with some basic information about how they should be run python enables you to do this with - python - usagepython [option[- cmd - mod file -[argoptions and arguments (and corresponding environment variable... |
10,892 | venture of iit bombay vjti alumni you can also program your script in such way that it should accept various options command line arguments is an advanced topic and should be studied bit later once you have gone through rest of the python concepts python variable types variables are nothing but reserved memory location... |
10,893 | venture of iit bombay vjti alumni #!/usr/bin/python counter an integer assignment miles floating point name "johna string print counter print miles print name here and "johnare the values assigned to countermilesand name variablesrespectively this produces the following result john multiple assignment python allows you... |
10,894 | venture of iit bombay vjti alumni = = = herean integer object is created with the value and all three variables are assigned to the same memory location you can also assign multiple objects to multiple variables for example , , , ,"johnheretwo integer objects with values and are assigned to variables and respectivelyan... |
10,895 | venture of iit bombay vjti alumni dictionary python numbers number data types store numeric values number objects are created when you assign value to them for example var var you can also delete the reference to number object by using the del statement the syntax of the del statement is del var [,var [,var ,varn]]]you... |
10,896 | venture of iit bombay vjti alumni complex (complex numbersexamples here are some examples of numbers int long float complex - - - - xdefabcecbdaecbfbael + - - + - - + |
10,897 | venture of iit bombay vjti alumni - - - python allows you to use lowercase with longbut it is recommended that you use only an uppercase to avoid confusion with the number python displays long integers with an uppercase complex number consists of an ordered pair of real floating-point numbers denoted by yjwhere and are... |
10,898 | venture of iit bombay vjti alumni print str prints complete string print str[ prints first character of the string print str[ : prints characters starting from rd to th print str[ :prints string starting from rd character print str prints string two times print str "testprints concatenated string this will produce the ... |
10,899 | venture of iit bombay vjti alumni lists are similar to arrays in one difference between them is that all the items belonging to list can be of different data type the values stored in list can be accessed using the slice operator (and [:]with indexes starting at in the beginning of the list and working their way to end... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.