csc 1010 lecture 5
play

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

CSC 1010 Lecture 5 What do we know so far? Class lecture, lab, Rephactor, Quick Checks, R&R Solve problems, computers useful, user vs. programmer CSC 1010 Programming for All Sequence of instructions, algorithm is


  1. CSC 1010 Lecture 5 What do we know so far? • Class – lecture, lab, Rephactor, Quick Checks, R&R • Solve problems, computers useful, user vs. programmer • CSC 1010 Programming for All Sequence of instructions, algorithm is step‐by‐step Python is 3 rd most popular language, core principles • • 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 Lecture 5 • Boolean expressions: ==, !‐, <, <=, >, >=, not, and, or • Working with Functions Input function, comparing strings, programming conventions • variable & function names lowercase, CONSTANTS, indent • while, for, range, augmented assignments, palindromes • Turtle Graphics, forward, left, right, pensize, pencolor, dot, circle • goto, penup, pendown, fillcolor, begin_fill, end_fill, speed • easter eggs? 2 1 2 Functions Calling Functions A function is a collection of programming statements that are When you call a function, the code inside the function is given a name. When you call (or invoke) a function, the executed. When done, execution picks up at the spot where it statements of the function are executed. was called. Functions can be: • called (or invoked) • user‐defined • built‐in • external, in a module A simple call to the print function is: pr i nt ( ' Hel l o, Uni ver se! ' ) 3 4 3 4 Calling Functions The import Statement Use the import statement to use external functions The arguments are what is passed into a function call: i m por t r andom m y_f unct i on( ar g1, ar g2, ar g3) num = r andom . r andi nt ( ) There must be an argument for each parameters in the pr i nt ( ' The num ber i s: ' , num ) function definition. To use external functions without needing to use their The print function is an example of a function that takes a module name to invoke them, use the from…import syntax variable number of arguments: f r om r andom i m por t * pr i nt ( ' Hel l o' ) num = r andi nt ( ) pr i nt ( ' Num ber : ' , 5, ' Let t er : ' , ' a' ) pr i nt ( ' The num ber i s: ' , num ) pr i nt ( ) These are two uses of import, but there are more To call external functions, you may need to import them first 5 6 5 6 1

  2. CSC 1010 Lecture 5 The import Statement Defining Functions A function definition has the following syntax: The various import statement syntaxes are: 7 8 7 8 Defining Functions Defining Functions Parameters are the names of variables in the function header: To return a value from a function, use the return statement. def m y_f unct i on( par am 1, par am 2, par am 3) : def m y_f unct i on( par am 1, par am 2, par am 3) : val ue = par am 1 * ( par am 2 + par am 3) r et ur n par am 1 * ( par am 2 + par am 3) r et ur n val ue When calling this function, arguments are passed in, one for Some value is calculated inside the function. The return each parameter in the function definition: statement returns it to the code that called it. r esul t = m y_f unct i on( 7, 9, 13) r esul t = m y_f unct i on( 7, 9, 13) pr i nt ( r esul t ) pr i nt ( r esul t ) When run, the output is: The value that was calculated inside the function is: 154 154 9 10 9 10 Defining Functions Defining Functions When you call a function that has positional arguments, you If a function accepts parameters, the parameter names are order you pass in arguments matters. listed in the function header inside the parentheses. who_am _i = m y_nam e( ' Sal l y' , ' Ri de' ) def m y_nam e( f i r st , l ast ) : pr i nt ( who_am _i ) nam e = f i r st + ' ' + l ast r et ur n nam e With arguments in the right order, you see this: Sal l y Ri de If arguments are in the wrong positions, you get this: Ri de Sal l y 11 12 11 12 2

  3. CSC 1010 Lecture 5 Defining Functions Defining Functions You can define default arguments for the function parameters. A keyword argument allows you to pass arguments in any order using the variable name of the parameter. def i ncr em ent _val ue( val ue, i nc = 1) : r et ur n val ue + i nc def pr i nt _nam e( f i r st _nam e, l ast _nam e) : pr i nt ( f i r st _nam e, l ast _nam e) pr i nt ( i ncr em ent _val ue( 7) ) pr i nt ( i ncr em ent _val ue( 5, 4) ) pr i nt _nam e( ' M ont y' , ' Pyt hon' ) pr i nt _nam e( f i r st _nam e = ' M ont y' , l ast _nam e = ' Hal l ' ) Default arguments are used if no value is passed in: pr i nt _nam e( l ast _nam e = ' Bur ns' , f i r st _nam e = ' M ont gom er y' ) 8 9 The first call uses positional arguments while the next two calls use keyword arguments, resulting in this output: They have to be in the right order, and you cannot have a parameter without a default value after one that has one: M ont y Pyt hon M ont y Hal l def bad_f unc( ar g1, ar g2=77, ar g3) : M ont gom er y Bur ns r et ur n ar g1 * ar g2 – ar g3 13 14 13 14 Defining Functions Defining Functions You can also define a function that takes a variable number of Any variables you create and use inside a function definition arguments. Precede the parameter with an asterisk (*) to are local variables. They can only be used inside that function. represent any number of arguments: def pr oduct ( * val ues) : t ot al = 1 def pr oduct ( * val ues) : t ot al = 1 f or num i n val ues: f or num i n val ues: t ot al * = num r et ur n t ot al t ot al * = num r et ur n t ot al In this example, total and num are local variables. Once the pr i nt ( pr oduct ( 4, 5) ) function returns, total and num no longer exist! pr i nt ( pr oduct ( 3, 5, 10, 6) ) They are local to the function. 20 900 15 16 15 16 String Methods String Methods String methods perform a variety of useful functions on strings Some of the most useful string methods are: st r i ng1 = ' Hel l o, W or l d! ' method what it does st r i ng2 = st r i ng1. l ower ( ) lower() make string all lowercase st r i ng3 = st r i ng1. upper ( ) upper() makes string all UPPERCASE pr i nt ( st r i ng2) pr i nt ( st r i ng3) strip() removes whitespace on both ends isalpha() does string contain only alphabetic characters? hel l o, wor l d! isdigit() does string contain only numeric characters? HELLO , W O RLD! islower() is string all lowercase? A method is a function associated with a particular type of isupper() is string all UPPERCASE? object. It is called through an object using the dot operator and performs some operation on that object. 17 18 17 18 3

  4. CSC 1010 Lecture 5 String Methods String Methods Some of the most useful, powerful string methods are: The split method is useful for tokenizing strings, breaking a sentence into a list of words, for example: method what it does split() splits a string at spaces into a list of strings sent = ' To be, or not t o be, t hat i s t he quest i on. ' wor ds = sent . spl i t ( ) split(sep) splits a string at any sep into a list of strings f or wor d i n wor ds: startswith(substr) does string begin with substr? pr i nt ( wor d) endswith(substr) does string end with substr? To find(substr) starting index of the first place in string where substr be, matches it, or ‐1 if none or not count(substr) how many times does substr appear in string? t o replace(s1, s2) replace s1 everywhere it appears is string with s2 be, t hat i s t he quest i on. 19 20 19 20 String Methods String Methods The replace method is helpful for cleaning up messy data, a Combining split and replace, we can make a list of uniform common problem in data analytics. The first argument is and more useful words: replaced with the second argument in the string. sent = ' To be, or not t o be, t hat i s t he quest i on. ' sent = sent . r epl ace( ' , ' , ' ' ) dat a = ' H#e% #* l #l * * #o% , # W * % o#r * l ###d! ' sent = sent . r epl ace( ' . ' , ' ' ) cl ean = dat a. r epl ace( ' #' , ' ' ) sent = sent . l ower ( ) cl ean = cl ean. r epl ace( ' % ' , ' ' ) wor ds = sent . spl i t ( ) cl ean = cl ean. r epl ace( ' * ' , ' ' ) f or wor d i n wor ds: pr i nt ( ' di r t y: ' + dat a) pr i nt ( wor d, end=' | ' ) pr i nt ( ' cl ean: ' + cl ean) t o | be | or | not | t o | be | t hat | i s | t he | quest i on | di r t y: H#e% #* l #l * * #o% , # W * % o#r * l ###d! cl ean: Hel l o, W or l d! 21 22 21 22 Built‐In Functions External Functions Python supports external functions (those in a different file) The Python Standard Library has a large number of ready to same as with built‐in functions, using the import statement: use functions that are built into Python, including: mycounter.py def wor d_count ( sent ence) : r et ur n l en( sent ence. spl i t ( ) ) myprog.py i m por t m ycount er sent = ' To be, or not t o be, t hat i s t he quest i on. ' pr i nt ( ' I see' , m ycount er . wor d_count ( sent ) , ' wor ds' ) Running myprog.py produces this output: I see 10 wor ds External functions can be ones that you write or download. 23 24 23 24 4

Recommend


More recommend