1 of 21

BASIC FUNCTIONS

2 of 21

FUNCTIONS

  • write reusable pieces/chunks of code, called functions
  • functions are not run in a program until they are “called” or “invoked” in a program
  • function characteristics:
    • has a name
    • has parameters (0 or more)
    • has a docstring (optional but recommended)
    • has a body
    • returns something

3 of 21

HOW TO WRITE and

CALL/INVOKE A FUNCTION

def

is_even( i ):

"""

Input: i:int, a positive number

Returns True if i is even, otherwise False """

print("inside is_even")

return i%2 == 0

is_even(3)

4 of 21

IN THE FUNCTION BODY

def is_even( i ): """

Input: i:int, a positive int

Returns True if i is even, otherwise False """

print("inside

is_even")

return

i%2

==

0

5 of 21

VARIABLE SCOPE

  • formal parameter gets bound to the value of

actual parameter when function is called

  • new scope/frame/environment created when enter a function
  • scope is mapping of names to objects

def f( x ):

x = x + 1

print('in f(x): x =', x) return x

x =

3

z =

f(

X

)

Variables with the same apparent name can reference different object in different places

Locality and persistence or lack thereof

6 of 21

VARIABLE SCOPE

Global scope

f

x

z

Some

code

3

4

def f( x ):

x = x + 1

print('in f(x): x =', x) return x

x = 3

z = f( x )

7 of 21

ONE WARNING IF NO

return STATEMENT

def is_even( i ):

"""

Input: i, a positive int Does not return anything """

i%2 == 0

  • Python returns the value None, if no return given
  • represents the absence of a value

8 of 21

EXERCISE: FIBONACCI NUMBER

 

9 of 21

MODULES

  • Each python file (xyz.py) is a module
  • can define variables, functions, types in a module
  • can modify the value of values in a module
  • Import modules using the ‘import’ keyword, one of two ways:

import xyz

xyz.stuff = 23

  • Or import into current namespace, caveat is have to use ‘global’ keyword to modify. Be careful of name collisions, error prone.

from xyz import *

def foo():

global stuff;

stuff = 23

  • Demo

10 of 21

DICTIONARIES

11 of 21

A PYTHON DICTIONARY

  • store pairs of data
    • key
    • value

my_dict = {}

grades = {'Ana':'B', 'John':'A+', 'Denise':'A', 'Katy':'A'}

Key 1

Key 2

Key 3

Val 1

Val 2

Val 3

key1 val1 key2 val2

key3 val3 key4 val4

'Ana'

'B'

'Denise'

'A'

'John'

'A+'

'Katy'

'A'

Also explain how to search by value

12 of 21

DICTIONARY LOOKUP

'Ana'

'B'

'Denise'

'A'

'John'

'A+'

'Katy'

'A'

  • similar to indexing into a list
  • looks up the key
  • returns the value associated with the key
  • if key isn’t found, get an error

grades = {'Ana':'B', 'John':'A+', 'Denise':'A', 'Katy':'A'}

grades['John'] grades['Sylvan']

evaluates to 'A+'

gives a KeyError

13 of 21

grades = {'Ana':'B', 'John':'A+', 'Denise':'A', 'Katy':'A'}

  • add an entry

grades['Sylvan'] = 'A'

  • test if key in dictionary

returns True

returns False

'John' in grades 'Daniel' in grades

  • delete entry

del(grades['Ana'])

DICTIONARY OPERATIONS

'Ana'

'B'

'Denise'

'A'

'John'

'A+'

'Katy'

'A'

'Sylvan'

'A'

14 of 21

grades = {'Ana':'B', 'John':'A+', 'Denise':'A', 'Katy':'A'}

  • get an iterable that acts like a tuple of all keys

grades.keys()

returns ['Denise','Katy','John','Ana']

  • get an iterable that acts like a tuple of all values

grades.values() returns ['A', 'A', 'A+', 'B']

DICTIONARY OPERATIONS

'Ana'

'B'

'Denise'

'A'

'John'

'A+'

'Katy'

'A'

Fix to make l=grades.keys() so a list not a tuple!!!!

Add grades.items…

15 of 21

DICTIONARY KEYS and VALUES

  • values
    • any type (immutable and mutable)
    • can be duplicates
    • dicSonary values can be lists, even other dicSonaries!
  • keys
    • must be unique
    • immutable type (int, float, string, tuple,bool)
      • actually need an object that is hashable, but think of as immutable as all immutable types are hashable
    • careful with float type as a key
  • no order to keys or values!

d = {4:{1:0}, (1,3):"twelve", 'const':[3.14,2.7,8.44]}

16 of 21

list

vs

dict

  • ordered sequence of elements
  • look up elements by an integer index
  • indices have an order
  • index is an integer
  • matches “keys” to “values”
  • look up one item by another item
  • no order is guaranteed
  • key can be any

immutable type

17 of 21

CREATING A DICTIONARY

def lyrics_to_frequencies(lyrics): myDict = {}

for word in lyrics:

if word in myDict: myDict[word] += 1

else:

myDict[word] = 1 return myDict

18 of 21

USING THE DICTIONARY

def most_common_words(freqs): values = freqs.values() best = max(values)

words = []

for k in freqs:

if freqs[k] == best: words.append(k)

return (words, best)

19 of 21

LEVERAGING DICTIONARY PROPERTIES

def words_often(freqs, minTimes): result = []

done = False while not done:

temp = most_common_words(freqs) if temp[1] >= minTimes:

result.append(temp) for w in temp[0]:

del(freqs[w])

else:

done = True return result

print(words_often(beatles, 5))

20 of 21

EXERCISE: CHARACTER COUNTING

  • Write a function that return a dictionary with the number of occurrences of each character in a string

21 of 21

Module Questionnaire

Support: NIH NIBIB-U24EB028887, NIGMS-R01GM122424, NSF-188553, NSF-186890, NSF-1720625, NIGMS-R01GM076692, NIGMS-R01GM077138

Please take a minute or two to let us know about your experience with this module by filling out the brief zoom survey

Feel free to provide additional comments and suggestions in the slack or by email to us as well (haydenfennell@gmail.com)