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

csc 1010 lecture 5
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

CSC 1010 Lecture 5 1

CSC 1010 Programming for All

Lecture 5 Working with Functions

What do we know so far?

  • Class – lecture, lab, Rephactor, Quick Checks, R&R
  • Solve problems, computers useful, user vs. programmer
  • Sequence of instructions, algorithm is step‐by‐step
  • Python is 3rd 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
  • Boolean expressions: ==, !‐, <, <=, >, >=, not, and, or
  • 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

Functions

A function is a collection of programming statements that are given a name. When you call (or invoke) a function, the statements of the function are executed. Functions can be:

  • called (or invoked)
  • user‐defined
  • built‐in
  • external, in a module

3

Calling Functions

When you call a function, the code inside the function is

  • executed. When done, execution picks up at the spot where it

was called.

4

A simple call to the print function is:

pr i nt ( ' Hel l o, Uni ver se! ' )

Calling Functions

The arguments are what is passed into a function call:

5

m y_f unct i on( ar g1, ar g2, ar g3)

There must be an argument for each parameters in the function definition. The print function is an example of a function that takes a variable number of arguments:

pr i nt ( ' Hel l o' ) pr i nt ( ' Num ber : ' , 5, ' Let t er : ' , ' a' ) pr i nt ( )

To call external functions, you may need to import them first

The import Statement

Use the import statement to use external functions

6

i m por t r andom num = r andom . r andi nt ( ) pr i nt ( ' The num ber i s: ' , num )

To use external functions without needing to use their module name to invoke them, use the from…import syntax

f r om r andom i m por t * num = r andi nt ( ) pr i nt ( ' The num ber i s: ' , num )

These are two uses of import, but there are more

1 2 3 4 5 6

slide-2
SLIDE 2

CSC 1010 Lecture 5 2

The import Statement

The various import statement syntaxes are:

7

Defining Functions

A function definition has the following syntax:

8

Defining Functions

Parameters are the names of variables in the function header:

9

def m y_f unct i on( par am 1, par am 2, par am 3) : r et ur n par am 1 * ( par am 2 + par am 3)

When calling this function, arguments are passed in, one for each parameter in the function definition: When run, the output is:

r esul t = m y_f unct i on( 7, 9, 13) pr i nt ( r esul t ) 154

Defining Functions

10

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) : val ue = par am 1 * ( par am 2 + par am 3) r et ur n val ue

Some value is calculated inside the function. The return statement returns it to the code that called it. The value that was calculated inside the function is:

r esul t = m y_f unct i on( 7, 9, 13) pr i nt ( r esul t ) 154

Defining Functions

11

If a function accepts parameters, the parameter names are listed in the function header inside the parentheses.

def m y_nam e( f i r st , l ast ) : nam e = f i r st + ' ' + l ast r et ur n nam e

Defining Functions

12

When you call a function that has positional arguments, you

  • rder you pass in arguments matters.

With arguments in the right order, you see this:

who_am _i = m y_nam e( ' Sal l y' , ' Ri de' ) pr i nt ( who_am _i ) Sal l y Ri de

If arguments are in the wrong positions, you get this:

Ri de Sal l y

7 8 9 10 11 12

slide-3
SLIDE 3

CSC 1010 Lecture 5 3

Defining Functions

13

You can define default arguments for the function parameters. Default arguments are used if no value is passed in:

def i ncr em ent _val ue( val ue, i nc = 1) : r et ur n val ue + i nc pr i nt ( i ncr em ent _val ue( 7) ) pr i nt ( i ncr em ent _val ue( 5, 4) )

They have to be in the right order, and you cannot have a parameter without a default value after one that has one:

8 9 def bad_f unc( ar g1, ar g2=77, ar g3) : r et ur n ar g1 * ar g2 – ar g3

Defining Functions

14

A keyword argument allows you to pass arguments in any

  • rder using the variable name of the parameter.

The first call uses positional arguments while the next two calls use keyword arguments, resulting in this output:

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 _nam e( ' M

  • nt y' , ' Pyt hon' )

pr i nt _nam e( f i r st _nam e = ' M

  • nt y' , l ast _nam

e = ' Hal l ' ) pr i nt _nam e( l ast _nam e = ' Bur ns' , f i r st _nam e = ' M

  • nt gom

er y' ) M

  • nt y Pyt hon

M

  • nt y Hal l

M

  • nt gom

er y Bur ns

Defining Functions

15

You can also define a function that takes a variable number of

  • arguments. Precede the parameter with an asterisk (*) to

represent any number of arguments:

def pr oduct ( * val ues) : t ot al = 1 f or num i n val ues: t ot al * = num r et ur n t ot al pr i nt ( pr oduct ( 4, 5) ) pr i nt ( pr oduct ( 3, 5, 10, 6) ) 20 900

Defining Functions

16

Any variables you create and use inside a function definition are local variables. They can only be used inside that function.

def pr oduct ( * val ues) : t ot al = 1 f or num i n val ues: t ot al * = num r et ur n t ot al

In this example, total and num are local variables. Once the function returns, total and num no longer exist! They are local to the function.

String Methods

17

st r i ng1 = ' Hel l o, W

  • r l d! '

st r i ng2 = st r i ng1. l ower ( ) st r i ng3 = st r i ng1. upper ( ) pr i nt ( st r i ng2) pr i nt ( st r i ng3)

String methods perform a variety of useful functions on strings

hel l o, wor l d! HELLO , W O RLD!

A method is a function associated with a particular type of

  • bject.

It is called through an object using the dot operator and performs some operation on that object.

String Methods

18

Some of the most useful string methods are:

method what it does lower() make string all lowercase upper() makes string all UPPERCASE strip() removes whitespace on both ends isalpha() does string contain only alphabetic characters? isdigit() does string contain only numeric characters? islower() is string all lowercase? isupper() is string all UPPERCASE?

13 14 15 16 17 18

slide-4
SLIDE 4

CSC 1010 Lecture 5 4

String Methods

19

Some of the most useful, powerful string methods are:

method what it does split() splits a string at spaces into a list of strings split(sep) splits a string at any sep into a list of strings startswith(substr) does string begin with substr? endswith(substr) does string end with substr? find(substr) starting index of the first place in string where substr matches it, or ‐1 if none count(substr) how many times does substr appear in string? replace(s1, s2) replace s1 everywhere it appears is string with s2

String Methods

20

sent = ' To be, or not t o be, t hat i s t he quest i on. ' wor ds = sent . spl i t ( ) f or wor d i n wor ds: pr i nt ( wor d)

To be,

  • r

not t o be, t hat i s t he quest i on.

The split method is useful for tokenizing strings, breaking a sentence into a list of words, for example:

String Methods

21

dat a = ' H#e% #* l #l * * #o% , # W * %

  • #r * l ###d! '

cl ean = dat a. r epl ace( ' #' , ' ' ) cl ean = cl ean. r epl ace( ' % ' , ' ' ) cl ean = cl ean. r epl ace( ' * ' , ' ' ) pr i nt ( ' di r t y: ' + dat a) pr i nt ( ' cl ean: ' + cl ean) di r t y: H#e% #* l #l * * #o% , # W * %

  • #r * l ###d!

cl ean: Hel l o, W

  • r l d!

The replace method is helpful for cleaning up messy data, a common problem in data analytics. The first argument is replaced with the second argument in the string.

String Methods

22

sent = ' To be, or not t o be, t hat i s t he quest i on. ' sent = sent . r epl ace( ' , ' , ' ' ) sent = sent . r epl ace( ' . ' , ' ' ) sent = sent . l ower ( ) wor ds = sent . spl i t ( ) f or wor d i n wor ds: pr i nt ( wor d, end=' | ' )

t o | be | or | not | t o | be | t hat | i s | t he | quest i on |

Combining split and replace, we can make a list of uniform and more useful words:

Built‐In Functions

The Python Standard Library has a large number of ready to use functions that are built into Python, including:

23

External Functions

Python supports external functions (those in a different file) same as with built‐in functions, using the import statement:

24

def wor d_count ( sent ence) : r et ur n l en( sent ence. spl i t ( ) ) mycounter.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' ) myprog.py

I see 10 wor ds

Running myprog.py produces this output: External functions can be ones that you write or download.

19 20 21 22 23 24