1 of 18

Functions

CS 149 Chapter 4 Base Slides

A couple of the slides in this set are adapted from the POGIL activities or from Prof Chao.

2 of 18

Basic Patterns of Program Flow

  • Sequence
    • Instructions are executed one after another
  • Selection (Conditionals)
    • A group of instructions may or may not be executed, depending on some condition
  • Function calls
    • Jump to the function at the function call
    • Return to the next step after the function call
  • Iteration (Loops)
    • A group of instructions is repeated multiple times

3 of 18

Functions

  • Function definition/implementation:

def functionName(arg_x, arg_y):

# everything indented is part of the function

x = arg_x + 2

y = arg_y * 2

# a return statement is optional

return (x + y)

  • Function call/invocation

functionName(17, 4)

4 of 18

Functions

Function

doSomething

Data in

Data out

5 of 18

Functions

Function

doSomething

Data in

Data out

Arguments (parameters)

Return value

6 of 18

Functions - compare to input/output

Function

doSomething

Data in

Data out

Arguments (parameters)

Return value

Program

input()

print()

Program

Program

7 of 18

Functions

  • Reuse the same code over and over
  • Write code for others to use
  • Function parameters
    • Allow the function to take the same action on different input data
  • Function return values
    • Use the output of a function in further computations
    • If there are no return statements in a function
      • The function returns special type None at its end

8 of 18

Function style and documentation

  • Two blank lines before & after each function
  • Function docstring

def divide(number, divisor):

"""

Calculate the quotient and remainder.

Args:

number(int): the number to divide

divisor(int): the divisor

Returns:

int: the quotient

int: the remainder

"""

9 of 18

Program flow

  • Default behavior is sequential
  • Functions change the flow

10 of 18

Python Programs

  • A Python program consists of one or more functions
  • Each function consists of one or more statements
  • Functions help organize programs into reusable blocks of code
    • Also more manageable and easier to understand

  • A statement may call (invoke) a function (or multiple functions)
    • When called, the function’s code begins to execute
    • When the function reaches a return statement (or it reaches its end), execution continues just after the point where the function was called
    • If a value(s) is returned, it is used in the expression where the function was called

11 of 18

Python Programs

  • A Python program may consist of multiple modules (.py files) of code
  • Modules may import other modules
    • Multiple files embedded into one another
    • Forming one large program

Where does a Python program start?

12 of 18

Where does a Python program start?

  • In most languages, a program starts with a function called main
  • If you execute a Python file, it will start at the first executable statement
    • The first unindented executable statement
    • Function definitions are not executable
  • Many Python programmers set up a main function like this

def main():

print("Hello World!")

if __name__ == "__main__":

main()

    • The special __name__ variable’s value distinguishes between whether the module is executed directly, or imported

https://realpython.com/python-main-function/

13 of 18

Program Flow

14

15

10

11

5

2

6

2

7

2

12

Order of execution

(by line #)

14 of 18

Scope

  • Local variables
    • Variables defined within a function
    • Function parameters are local to a function
  • Global variables
    • Variables defined outside of a function
    • Can be accessed from inside functions
    • To change a global variable inside a function requires a special global statement

15 of 18

Global variables

student_id = 1000

def define_student(fname, lname):

global student_id # required to change the global

eid = lname[0:6] + fname[0:2]

email = eid + "@dukes.jmu.edu"

student_id += 1;

return student_id, eid, email

print(define_student("mona", "rizvi"))

print(define_student("james", "madison"))

16 of 18

Function parameters and arguments

  • If a function call argument is immutable,
    • If the local variable (parameter) is modified, a new object is created
    • Simple data types (int, float, bool, etc.) are immutable
  • If a function call argument is mutable,
    • If the local variable is modified, the original object is changed
    • More on this later …

17 of 18

Multiple returns

student_id = 1000

def define_student(fname, lname):

global student_id

eid = lname[0:6] + fname[0:2]

email = eid + "@dukes.jmu.edu"

student_id += 1;

return student_id, eid, email

x = define_student("james", "madison")

print(x[0])

print(x[2])

18 of 18

Multiple returns

  • It appears that you are returning many values separated by commas
  • A series of values separated by commas automatically creates a tuple