id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
9,200 | indexing we will often want to pick out individual characters from string python uses square brackets to do this the table below gives some examples of indexing the string ='pythonstatement result description [ first character of [ second character of [- last character of [- second-to-last character of the first charac... |
9,201 | strings the basic structure is string name[starting location ending location+ slices have the same quirk as the range function in that they do not include the ending location for instancein the example aboves[ : gives the characters in indices and but not the character in index we can leave either the starting or endin... |
9,202 | for in sprint(cthis loop will step through scharacter by characterwith holding the current character you can almost read this like an english sentence"for every character in sprint that character string methods strings come with ton of methodsfunctions that return information about the string or return new string that ... |
9,203 | strings if [ isalpha()print'your string starts with letter 'if not isalpha()print'your string contains non-letter ' note about index if you try to find the index of something that is not in stringpython will raise an error for instanceif ='abcand you try index(' ')you will get an error one way around this is to check f... |
9,204 | \ this is used to get the backslash itself for examplefilename ' :\\programs\\file py \ the tab character examples example an easy way to print blank line is print(howeverif we want to print ten blank linesa quick way to do that is the followingprint'\ '* note that we get one of the ten lines from the print function it... |
9,205 | strings we will require loop because we have to repeatedly print sections of the stringand to print the sections of the stringwe will use slicename input'enter your name'for in range(len(name))print(name[: + ]end'the one trick is to use the loop variable in the slice since the number of characters we need to print is c... |
9,206 | example simple and very old method of sending secret messages is the substitution cipher basicallyeach letter of the alphabet gets replaced by another letter of the alphabetsay every gets replaced with an xand every gets replaced by zetc write program to implement this alphabet 'abcdefghijklmnopqrstuvwxyz key 'xznlwebg... |
9,207 | strings (kthe string with every letter replaced by space simple way to estimate the number of words in string is to count the number of spaces in the string write program that asks the user for string and returns an estimate of how many words are in the string people often forget closing parentheses when entering formu... |
9,208 | write program that asks the user to enter word that contains the letter the program should then print the following two lineson the first line should be the part of the string up to and including the first aand on the second line should be the rest of the string sample output is shown belowenter wordbuffalo buffa lo wr... |
9,209 | strings dear george washingtoni am pleased to offer you our new platinum plus rewards card at special introductory apr of georgean offer like this does not come along every dayso urge you to call now toll-free at - we cannot offer such low rate for longgeorgeso call right away write program that generates the -line blo... |
9,210 | simple way of encrypting message is to rearrange its characters one way to rearrange the characters is to pick out the characters at even indicesput them first in the encrypted stringand follow them by the odd characters for examplethe string message would be encrypted as msaeesg because the even characters are msae (a... |
9,211 | strings |
9,212 | lists say we need to get thirty test scores from user and do something with themlike put them in order we could create thirty variablesscore score score but that would be very tedious to then put the scores in order would be extremely difficult the solution is to use lists basics creating lists here is simple listl [ ,... |
9,213 | lists printing lists you can use the print function to print the entire contents of list [ , , print( [ data types valid listlists can contain all kinds of thingseven other lists for examplethe following is [ 'abc '[ , , ] similarities to strings there are number of things which work the same way for lists as for strin... |
9,214 | built-in functions there are several built-in functions that operate on lists here are some useful onesfunction description len returns the number of items in the list sum returns the sum of the items in the list min returns the minimum of the items in the list max returns the maximum of the items in the list for examp... |
9,215 | lists miscellaneous making copies of lists making copies of lists is little tricky due to the way python handles lists say we have list and we want to make copy of the list and call it the expression = will not work for reasons covered in section for nowdo the following in place of =lm [:changing lists changing specifi... |
9,216 | count for item in lif item> count=count+ example given list that contains numbers between and create new list whose first element is how many ones are in lwhose second element is how many twos are in letc frequencies [for in range( , )frequences append( count( )the key is the list method count that tells how many times... |
9,217 | lists the code worksbut it is very tedious if we want to add more questionswe have to copy and paste one of these blocks of code and then change bunch of things if we decide to change one of the questions or the order of the questionsthen there is fair amount of rewriting involved if we decide to change the design of t... |
9,218 | (gprint how many integers in the list are less than write program that generates list of random numbers between and (aprint the list (bprint the average of the elements in the list (cprint the largest and smallest values in the list (dprint the second largest and second smallest entries in the list (eprint how many eve... |
9,219 | lists write program that rotates the elements of list so that the element at the first index moves to the second indexthe element in the second index moves to the third indexetc and the element in the last index moves to the first index using for loopcreate the list belowwhich consists of ones separated by increasingly... |
9,220 | more with lists lists and the random module there are some nice functions in the random module that work on lists function description choice(lpicks random item from sample( ,npicks group of random items from shuffle(lshuffles the items of note the shuffle function modifies the original listso if you don' want your lis... |
9,221 | more with lists example the choice function also works with stringspicking random character from string here is an example that uses choice to fill the screen with bunch of random characters from random import choice 'abcdefghijklmnopqrstuvwxyz !@#$%^&*(for in range( )print(choice( )end''example here is nice use of shu... |
9,222 | from string import punctuation for in punctuations replace( ''example here is program that counts how many times certain word occurs in string from string import punctuation input'enter string'for in punctuations replace( '' lower( split(word input'enter word'print(word'appears ' count(word)'times 'optional argument th... |
9,223 | more with lists this sounds like something we could use shuffle forbut shuffle only works with lists what we need to do is convert our string into listuse shuffle on itand then convert the list back into string to turn string into listwe can use list( (see section to turn the list back into stringwe will use join from ... |
9,224 | [[ ,jfor in range( for in range( )[[ ][ ][ ][ ]this is the equivalent of the following codel [for in range( )for in range( ) append([ , ]here is another example[[ ,jfor in range( for in range( )[[ ][ ][ ][ ][ ][ ] using list comprehensions to further demonstrate the power of list comprehensionswe will do the first four... |
9,225 | more with lists one more example suppose we have list whose elements are lists of size like belowl [[ , ][ , ][ , ]if we want to flip the order of the entries in the listswe can use the following list comprehensionm [[ ,xfor , in [[ ][ ][ ]note you can certainly get away without using list comprehensionsbut once you ge... |
9,226 | count for in range( )for in range( )if [ ][ ]% == count count this can also be done with list comprehensioncount sum([ for in range( for in range( if [ ][ ]% == ]creating large two-dimensional lists belowto create larger listyou can use list comprehension like [[ ]* for in range( )this creates list of zeroes with rows ... |
9,227 | more with lists exercises write program that asks the user to enter some text and then counts how many articles are in the text articles are the words ' ''an'and 'the write program that allows the user to enter five numbers (read as stringscreate string that consists of the user' numbers separated by plus signs for ins... |
9,228 | section described how to use the shuffle method to create random anagram of string use the choice method to create random anagram of string write program that gets string from the user containing potential telephone number the program should print valid if it decides the phone number is real phone numberand invalid oth... |
9,229 | more with lists write program that creates and prints an list whose entries alternate between and in checkerboard patternstarting with in the upper left corner write program that checks to see if list is magic square in magic squareevery rowcolumnand the two diagonals add up to the same value write program that asks th... |
9,230 | while loops we have already learned about for loopswhich allow us to repeat things specified number of times sometimesthoughwe need to repeat somethingbut we don' know ahead of time exactly how many times it has to be repeated for instancea game of tic-tac-toe keeps going until someone wins or there are no more moves t... |
9,231 | while loops get to the while statementtry to see if temp is not equal to - and run into problem because temp doesn' yet exist to take care of thiswe just declare temp equal to there is nothing special about the value here we could set it to anything except - (setting it to - would cause the condition on the while loop ... |
9,232 | example we can use while loop to mimic for loopas shown below both loops have the exact same effect for in range( )print(ii= while < print(ii= + remember that the for loop starts with the loop variable equal to and ends with it equal to to use while loop to mimic the for loopwe have to manually create our own loop vari... |
9,233 | while loops code below while < print(ii= + print'bye'the variable gets set to to start nextthe program tests the condition on the while loop because is which is less than the code indented under the while statement will get executed this code prints the current value of and then executes the statement = + which adds to... |
9,234 | example here is program that allows the user to enter up to numbers the user can stop early by entering negative number for in range( )num eval(input'enter number')if num< break this could also be accomplished with while loop = num= while num eval(input'enter number')either method is ok in many cases the break statemen... |
9,235 | while loops the program allows the user to enter up to numbers if they enter negativethen the program prints stopped early and asks for no more numbers if the user enters no negativesthen the program prints user entered all ten values example here are two ways to check if an integer num is prime prime number is number ... |
9,236 | lower guesses left enter your guess ( - ) lower guesses left enter your guess ( - ) higher guesses left enter your guess ( - ) lower guesses left you lose the correct number is firstthink about what we will need in the programwe need random numbersso there will be an import statement at the beginning of the program and... |
9,237 | while loops if guess secret_numprint'higher ' -num_guesses'guesses left \ 'elif guess secret_numprint'lower ' -num_guesses'guesses left \ 'elseprint'you got it'finallyit would be nice to have message for the player if they run out of turns when they run out of turnsthe while loop will stop looping and program control w... |
9,238 | exercises the code below prints the numbers from to rewrite the code using while loop to accomplish the same thing for in range( , )print( (awrite program that uses while loop (not for loopto read through string and print the characters of the string one-by-one on separate lines (bmodify the program above to print out ... |
9,239 | while loops -year old method to compute the square root of is as followsstart with an initial guesssay then compute nexttake that and replace the ' in the previous formula with ' this gives / next replace the in the previous formula with / this gives / / if you keep doing this process of computing the formulagetting re... |
9,240 | write text-based version of the game memory the game should generate board (see the exercise from initially the program should display the board as grid of asterisks the user then enters the coordinates of cell the program should display the grid with the character at those coordinates now displayed the user then enter... |
9,241 | while loops |
9,242 | miscellaneous topics ii in this we will look at variety of useful things to know strintfloatand list the strintfloatand list functions are used to convert one data type into another str quite often we will want to convert number to string to take advantage of string methods to break the number apart the built-in functi... |
9,243 | miscellaneous topics ii list the list function takes something that can be converted into list and makes into list here are two uses of it list(range( )list('abc'[ , , , , [' ',' ',' 'examples example here is an example that finds all the palindromic numbers between and palindromic number is one that is the same backwa... |
9,244 | example to break decimal numbernumup into its integer and fractional partswe can do the followingipart int(numdpart num int(numfor exampleif num is then ipart is and dpart is example if we want to check to see if number is primewe can do so by checking to see if it has any divisors other than itself and in section we s... |
9,245 | miscellaneous topics ii we have seen booleans before the isalpha string method returns true if every character of the string is letter and false otherwise shortcuts shortcut operators operations like count=count+ occur so often that there is shorthand for them here are couple of examplesstatement shorthand count=count+... |
9,246 | short-circuiting say we are writing program that searches list of words for those whose fifth character is 'zwe might try the followingfor in wordsif [ ]=' 'print(wbut with thiswe will occasionally get string index out of range error the problem is that some words in the list might be less than five characters long the... |
9,247 | miscellaneous topics ii string formatting suppose we are writing program that calculates tip on bill of $ when we multiplywe get but we would like to display the result as $ not $ here is how to do ita print'the tip is { fformat( )this uses the format method of strings here is another examplebill tip print'tip${ }total... |
9,248 | formatting floats to format floating point numberthe formatting code is {:fto only display the number to two decimal placesuse { fthe can be changed to change the number of decimal places you can right-justify floats for example{: fwill allot eight spots for its value--one of those is for the decimal point and two are ... |
9,249 | miscellaneous topics ii example common math problem is to find the solutions to system of equations sometimes you want to find only the integer solutionsand this can be little tricky mathematically howeverwe can write program that does brute force search for solutions here we find all the integer solutions (xyto the sy... |
9,250 | example your computer screen is grid of pixels to draw images to the screenwe often use nested for loops--one loop for the horizontal directionand one for the vertical direction see sections and for examples example list comprehensions can contain nested for loops the example below returns list of all the vowels in lis... |
9,251 | miscellaneous topics ii adding certain numbers to their reversals sometimes produces palindromic number for instance sometimeswe have to repeat the process for instance and write program that finds both two-digit numbers for which this process must be repeated more than times to obtain palindromic number write program ... |
9,252 | the currency of strange country has coins worth cents and cents write program to determine the largest purchase price that cannot be paid using these two coins here is an old puzzle you can solve using brute force by using computer program to check all the possibilitiesin the calculation every digit is precisely one aw... |
9,253 | miscellaneous topics ii given two dates entered as strings in the form mm/dd/yyyy where the years are between and determine how many days apart they are here is bit of information that may be usefulleap years between and occur exactly every four yearsstarting at february has days during leap year novemberapriljuneand s... |
9,254 | dictionaries dictionary is more general version of list here is list that contains the number of days in the months of the yeardays [ if we want the number of days in januaryuse days[ december is days[ or days[- here is dictionary of the days in the months of the yeardays 'january ': 'february ': 'march ': 'april ': 'm... |
9,255 | dictionaries to change [' 'to do ' ']= to add new entry to the dictionarywe can just assign itlike belowd' ']= note that this sort of thing does not work with lists doing [ ]= on list with two elements would produce an index out of range error but it does work with dictionaries to delete an entry from dictionaryuse the... |
9,256 | to score wordwe can do the followingscore sum([points[cfor in word]orif you prefer the long waytotal for in wordtotal +points[cexample dictionary provides nice way to represent deck of cardsdeck ['value ': 'suit ':cfor in 'spades ''clubs ''hearts ''diamonds 'for in range( , )the deck is actually list of dictionaries th... |
9,257 | dictionaries looping looping through dictionaries is similar to looping through lists here is an example that prints the keys in dictionaryfor key in dprint(keyhere is an example that prints the valuesfor key in dprint( [key]lists of keys and values the following table illustrates the ways to get lists of keys and valu... |
9,258 | in section we will learn how to read from text file for nowhere' line of code that reads the entire contents of file containing the text of shakespeare' romeo and juliet and stores the contents in string called texttext open'romeoandjuliet txt 'read(to get at the individual wordswe will use the split method to turn the... |
9,259 | dictionaries text text lower(for in punctuationtext text replace( ''words text split(build the dictionary of frequencies {for in wordsif in dd[wd[ elsed[ print in alphabetical order items list( items()items sort(for in itemsprint(iprint in order from least to most common items list( items()items [( [ ] [ ]for in itemsi... |
9,260 | (emodify the program from part (aand the dictionary so that the user does not have to know how to spell the month name exactly that isall they have to do is spell the first three letters of the month name correctly write program that uses dictionary that contains ten user names and passwords the program should ask the ... |
9,261 | dictionaries aetc write program that asks the user to enter two strings then determine if the second string could be an encoded version of the first one with substitution cipher for instancecxyz is not an encoded version of book because got mapped to two separate letters alsocxxk is not an encoded version of bookbecaus... |
9,262 | the following problem is from try it againthis time using dictionary whose keys are the names of the time zones and whose values are offsets from the eastern time zone write program that converts time from one time zone to another the user enters the time in the usual american waysuch as : pm or : am the first time zon... |
9,263 | dictionaries |
9,264 | text files there is ton of interesting data to be found on the internet stored in text files in this we will learn how to work with data stored in text files reading from files suppose we have text file called example txt whose contents are shown belowand we want to read its contents into python there are several ways ... |
9,265 | text files directories say your program opens filelike belows open'file txt 'read(the file is assumed to be in the same directory as your program itself if it is in different directorythen you need to specify thatlike belows open' :/users/heinold/desktop/file txt 'read( writing to files there are also several ways to w... |
9,266 | pythonthey can easily create their own lists of questions and answers to do thiswe just replace the lines that create the lists with the followingquestions [line strip(for line in open'questions txt ')answers [line strip(for line in open'answers txt ')example say you have text file that contains the results of every - ... |
9,267 | text files assuming the wordlist file is wordlist txtwe can load the words into list using the line below wordlist [line strip(for line in open'wordlist txt ')example print all three letter words for word in wordlistif len(word)== print(wordnote that this and most of the upcoming examples can be done with list comprehe... |
9,268 | note this is not very efficient way of doing things since we have to scan through most of the list binary search would be more efficientbut the above approach still runs almost instantly even for large files example find the longest word that can be made using only the letters abcdand largest for word in wordlistfor in... |
9,269 | text files each line has three entries separated by commasa usernamea log-on timeand log-off time times are given in -hour format you may assume that all log-ons and log-offs occur within single workday write program that scans through the file and prints out all users who were online for at least an hour you are given... |
9,270 | (efind all the teams that had winning records but were collectively outscored by their opponents team is collectively outscored by their opponents if the total number of points the team scored over all their games is less than the total number of points their opponents scored in their games against the team benford' la... |
9,271 | text files (xall words of the form abcd*dcbawhere is arbitrarily long sequence of letters (yall groups of wordslike pat pet pit pot putwhere each word is lettersall words share the same first and last lettersand the middle letter runs through all vowels (zthe word that has the most ' write program to help with word gam... |
9,272 | the file high_temperatures txt contains the average high temperatures for each day of the year in certain city each line of the file consists of the datewritten in the month/day formatfollowed by space and the average high temperature for that date find the -day period over which there is the biggest increase in the av... |
9,273 | text files |
9,274 | functions functions are useful for breaking up large program to make it easier to read and maintain they are also useful if you find yourself writing the same code at several different points in your program you can put that code in function and call the function whenever you want to execute that code you can also use ... |
9,275 | functions **************************put the code into functionand then whenever you need boxjust call the function rather than typing several lines of redundant code here is the function def draw_square()print' print'''* ''print'''* ''print' one benefit of this is that if you decide to change the size of the boxyou jus... |
9,276 | hellohellohellohellohello aaaaaaaaaa returning values we can write functions that perform calculations and return result example here is simple function that converts temperatures from celsius to fahrenheit def convert( )return * / + print(convert( ) the return statement is used to send the result of function' calculat... |
9,277 | functions xsolysol solve( , , , , , print'the solution is 'xsol'and 'ysolthe solution is and - this method uses the shortcut for assigning to lists that was mentioned in section example return statement by itself can be used to end function early def multiple_print(stringnbad_words)if string in bad_wordsreturn print(st... |
9,278 | fancy_print(text'hi 'style'bold 'justify'left 'background'black 'color'yellow 'as we can seethe order of the arguments does not matter when you use keyword arguments when defining the functionit would be good idea to give defaults for instancemost of the timethe caller would want left justificationa white backgroundetc... |
9,279 | functions def reset()global time_left time_left def print_time()print(time_lefttime_left= in this program we have variable time_left that we would like multiple functions to have access to if function wants to change the value of that variablewe need to tell the function that time_left is global variable we use global ... |
9,280 | func ( exercises write function called rectangle that takes two integers and as arguments and prints out an box consisting of asterisks shown below is the output of rectangle( , ****** (awrite function called add_excitement that takes list of strings and adds an exclamation point (!to the end of each string in the list... |
9,281 | functions write function called matches that takes two strings as arguments and returns how many matches there are between the strings match is where the two strings have the same character at the same index for instance'pythonand 'pathmatch in the firstthirdand fourth charactersso the function should return recall tha... |
9,282 | write function called verbose thatgiven an integer less than returns the name of the integer in english as an exampleverbose( should return one hundred twenty-three thousandfour hundred fifty-six write function called merge that takes two already sorted lists of possibly different lengthsand merges them into single sor... |
9,283 | functions |
9,284 | object-oriented programming about year or so after started programmingi decided to make game to play wheel of fortune wrote the program in the basic programming language and it got to be pretty largea couple thousand lines it mostly workedbut whenever tried to fix somethingmy fix would break something in completely dif... |
9,285 | object-oriented programming creating your own classes class is template for objects it contains the code for all the object' methods simple example here is simple example to demonstrate what class looks like it does not do anything interesting class exampledef __init__(selfab)self self def add(self)return self self exa... |
9,286 | lower(self words split(def number_of_words(self)return len(self wordsdef starts_with(selfs)return len([ for in self words if [:len( )]== ]def number_with_length(selfn)return len([ for in self words if len( )== ] 'this is test of the class analyzer analyzer(sprint(analyzer wordsprint'number of words'analyzer number_of_w... |
9,287 | object-oriented programming inheritance in object-oriented programming there is concept called inheritance where you can create class that builds off of another class when you do thisthe new class gets all of the variables and methods of the class it is inheriting from (called the base classit can then define additiona... |
9,288 | if the child class adds some new variablesit can call the parent class' constructor as demonstrated below another use is if the child class just wants to add on to one of the parent' methods in the example belowthe child' print_var method calls the parent' print_var method and adds an additional line class parentdef __... |
9,289 | object-oriented programming return '{of {format(self valueself suitelsereturn '{of {format(names[self value- ]self suitnext we have class to represent group of cards its data consists of list of card objects it has number of methodsnextcard which removes the first card from the list and returns ithascard which returns ... |
9,290 | for in range( , )self cards append(card(vs) pinochle deck has only ninestensjacksqueenskingsand aces there are two copies of each card in each suit here is the hi-low program that uses the classes we have developed here one way to think of what we have done with the classes is that we have built up miniature card progr... |
9,291 | object-oriented programming higher (hor lower ( ) rightthat' in row tic-tac-toe example in this section we create an object-oriented tic-tac-toe game we use class to wrap up the logic of the game the class contains two variablesan integer representing the current playerand list representing the board the board variable... |
9,292 | for in range( )if self [ ][ ]==self [ ][ ]==self [ ][ ]!= return self [ ][cfor in range( )if self [ ][ ]==self [ ][ ]==self [ ][ ]!= return self [ ][ if self [ ][ ]==self [ ][ ]==self [ ][ ]!= return self [ ][ if self [ ][ ]==self [ ][ ]==self [ ][ ]!= return self [ ][ if self get_open_spots()==[]return return - this c... |
9,293 | object-oriented programming enter spotplayer , enter spotplayer further topics special methods -we have seen two special methods alreadythe constructor __init__ and the method __str__ which determines what your objects look like when printed there are many others for instancethere is __add__ that allows your object to ... |
9,294 | is charged for orders of less than itemsa discount is applied for orders of between and itemsand discount is applied for orders of or more items there should also be method called make_purchase that receives the number of items to be bought and decreases amount by that much write class called password_manager the class... |
9,295 | object-oriented programming write class that inherits from the card_group class of this the class should represent deck of cards that contains only hearts and spaceswith only the cards through in each suit add method to the class called next that returns the top two cards from the deck write class called rock_paper_sci... |
9,296 | graphics |
9,297 | gui programming with tkinter up until nowthe only way our programs have been able to interact with the user is through keyboard input via the input statement but most real programs use windowsbuttonsscrollbarsand various other things these widgets are part of what is called graphical user interface or gui this is about... |
9,298 | gui programming with tkinter root tk(message_label label(text'enter temperature 'font='verdana ' )output_label label(font='verdana ' )entry entry(font='verdana ' )width= calc_button button(text'ok 'font='verdana ' )command=calculatemessage_label grid(row= column= entry grid(row= column= calc_button grid(row= column= ou... |
9,299 | fg and bg -these stand for foreground and background many common color names can be usedlike 'blue''green'etc section describes how to get essentially any color width -this is how many characters long the label should be if you leave this outtkinter will base the width off of the text you put in the label this can make... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.