csc 1010 lecture 8
play

CSC 1010 Lecture 8 What do we know so far? Class lecture, lab, - PDF document

CSC 1010 Lecture 8 What do we know so far? Class lecture, lab, Rephactor, Quick Checks, R&R, easter eggs Solve problems, computers useful, user vs. programmer Sequence of instructions, algorithm is step by step CSC


  1. CSC 1010 Lecture 8 What do we know so far? Class – lecture, lab, Rephactor, Quick Checks, R&R, easter eggs • Solve problems, computers useful, user vs. programmer • • Sequence of instructions, algorithm is step ‐ by ‐ step CSC 1010 Programming for All Python is 3 rd most popular language, core principles, always more than one way • • Syntax, runtime, & logic errors, testing & debugging, hardware vs. software • Control flow – step ‐ by ‐ step, function call, conditional, loop • IDLE shell, editor, install Python, Hello World • Intrepreter, compiler, Python Standard Library • Variables, assignment, numeric expr., precedence • Print function, Strings, concatenation, indexes, in, * • Interactive programs, if, if ‐ else, if ‐ elif ‐ else, int, float • Boolean expressions: ==, ! ‐ , <, <=, >, >=, not, and, or • Input function, comparing strings, programming conventions • Variable & function names lowercase, CONSTANTS, indent Lecture 8 • while, for, range, augmented assignments, palindromes • Turtle Graphics, forward, left, right, pensize, pencolor, dot, circle Dictionaries • goto, penup, pendown, fillcolor, begin_fill, end_fill, speed • Calling & defining functions, import, parameters vs. arguments, return • Positional args, default args, variable args, keyword args, local variables • String methods, replace, method vs. function, built ‐ in & external functions • Using loops and functions to create graphics, random numbers, design process • Lists: indexing, iterating, concatenating, containment, repetition • Membership: in & not in, Identity: is & is not, type checking • List algorithms, list methods, slicing strings and lists, ex: finding a minimum 2 1 2 Dictionaries Uses of Dictionaries A Python dictionary is an unordered, changeable, and indexed • Map a U.S. state name to its capital city. collection of keys and corresponding values. • Map a membership number to the corresponding member. • Map a sports team to the name of the city in which that team is based. • Map a word to its frequency count (how often that word is found in some text). • Map a zip code to the corresponding city name (or other location description). • Map a software version number to the year it was released. The keys and values can be of any type. Often, each key are • Map an English word to the corresponding French word. a single string or integer. The types of each value are more • Map a manager to the list of employees that work for that varied, such as strings, integers, and lists of multiple values. manager. • Map a course id to the list of students taking that course. 3 4 3 4 Creating Dictionaries Looking Up Values You define a dictionary in Python with curly braces ({}): The values in a dictionary can be accessed individually using a key inside the index operator. capi t al s = { } cap = capi t al s[ ' New Yor k' ] Initializing a dictionary with keys and values works like this: pr i nt ( ' The capi t al of New Yor k i s' , cap) capi t al s = { ' M ar yl and' : ' Annapol i s' , The capi t al of New Yor k i s Al bany ' New Yor k' : ' Al bany' , ' Cal i f or ni a' : ' Sacr am ent o' , If the value is not found, a KeyError is reported. The safer way ' Del awar e' : ' Dover ' } The dict function also works with named arguments: pr i nt ( capi t al s) is using get, which returns a None value if the key is missing. pr i nt ( ' I know' , l en( capi t al s) , ' st at e capi t al s! ' ) pr i nt ( " Del awar e' s capi t al i s" , capi t al s. get ( ' Del awar e' ) ) { ' Cal i f or ni a' : ' Sacr am ent o' , ' New Yor k' : ' Al bany' , ' M ar yl and' : ' Annapol i s' , ' Del awar e' : ' Dover ' } Del awar e' s capi t al i s Dover I know 4 st at e capi t al s! 5 6 5 6 1

  2. CSC 1010 Lecture 8 Changing and Adding Entries Removing Entries To change the value of a dictionary entry, use its key. To remove the value of a dictionary entry, use its key. capi t al s[ ' New Yor k' , ' Bi sm ar k' ] capi t al s. pop( ' Vi r gi ni a' ) pr i nt ( " New Yor k' s capi t al i s" , capi t al s[ ' New Yor k' ] ) pr i nt ( capi t al s) New Yor k' s capi t al i s Bi sm ar k The capitals dictionary will no longer have the removed entry. An entry can also be removed using del. This replaces the value for 'New York' with a new one. del capi t al s[ ' Vi r gi ni a' ] To add a new entry to the dictionary, use a new key: Use clear to remove all entries in a dictionary. capi t al s[ ' Texas' ] = ' Aust i n' capi t al s. cl ear ( ) pr i nt ( ' The capi t al of Texas i s' , capi t al s[ ' Texas' ] ) The capi t al of Texas i s Aust i n 7 8 7 8 Key Existence Iterating a Dictionary To avoid a KeyError when accessing a dictionary element that Iterate the keys in a dictionary using a for loop. doesn't exist, use the in operator. f or key i n capi t al s: pr i nt ( key) i f ' Fl or i da' i n capi t al s: pr i nt ( ' Fl or i da' s capi t al : ' , capi t al s[ ' Fl or i da' ] ) Iterate the values in a dictionary with the values method. el se: pr i nt ( " I don' t know t he capi t al of Fl or i da! " ) f or val ue i n capi t al s. val ues( ) : pr i nt ( val ue) I don' t know t he capi t al of Fl or i da! A common way to iterate keys and values is this: You can also use the not in operator on a dictionary, which f or key i n capi t al s: returns true if the key is not in the dictionary. pr i nt ( capi t al s[ key] , ' i s capi t al of ' , key) 9 10 9 10 Dictionary Methods Reading Text Files To read input from a text file, use open and read. The open method creates a file object using a filename. The read method reads all text from the file into a string. f i l e = open( ' i nput _dem o. t xt ' , ' r ' ) t ext = f i l e. r ead( ) pr i nt ( t ext ) Use readline to read one line at a time. whi l e Tr ue: l i ne = f i l e. r eadl i ne( ) i f l i ne == ' ' : br eak Use readlines to read all lines into a list of strings. l i nes = f i l e. r eadl i nes( ) 11 12 11 12 2

  3. CSC 1010 Lecture 8 Writing Text Files File Choosers: Open To write output to a text file, use open and write. The open The askopenfilename method opens a file selection dialog. method needs a 'w' argument to indicate the file is for writing. f r om t ki nt er i m por t Tk f r om t ki nt er . f i l edi al og i m por t askopenf i l enam e f i l e = open( ' l yr i cs. t xt ' , ' w' ) Tk( ) . wi t hdr aw( ) # Hi des t he def aul t wi ndow f i l e. wr i t e( ' Hel l o, W or l d! \ n' ) f i l e. wr i t e( ' And hel l o t o you! \ n' ) f i l enam e = askopenf i l enam e( ) f i l e. cl ose( ) Note the newline (\n) character is used to end each line. It is important to close the file when you are done writing. 13 14 13 14 File Choosers: Save File Choosers: Directory The asksaveasfilename method opens a file saving dialog. The askdirectory method opens a directory chooser dialog. f r om t ki nt er i m por t Tk f r om t ki nt er i m por t Tk f r om t ki nt er . f i l edi al og i m por t asksaveasf i l enam e f r om t ki nt er . f i l edi al og i m por t asksaveasf i l enam e Tk( ) . wi t hdr aw( ) # Hi des t he def aul t wi ndow Tk( ) . wi t hdr aw( ) # Hi des t he def aul t wi ndow f i l enam e = asksaveasf i l enam e( ) di r nam e = askdi r ect or y( ) 15 16 15 16 Example: Counting Letters An entry in the counts dictionary is created or incremented for each character. The for loop iterates through each character. t ext = ' ' ' I have a dr eam t hat m y f our l i t t l e chi l dr en wi l l one day l i ve i n a nat i on wher e t hey wi l l not be j udged by t he col or of t hei r ski n but by t he cont ent of t hei r char act er . ' ' ' count s = { } f or l et t er i n t ext . upper ( ) : i f l et t er . i sal pha( ) : i f l et t er not i n count s: count s[ l et t er ] = 1 el se: count s[ l et t er ] += 1 pr i nt ( ' Let t er f r equenci es: ' ) pr i nt ( count s) 17 17 3

Recommend


More recommend