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.
Basic Patterns of Program Flow
Functions
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)
functionName(17, 4)
Functions
Function
doSomething
Data in
Data out
Functions
Function
doSomething
Data in
Data out
Arguments (parameters)
Return value
Functions - compare to input/output
Function
doSomething
Data in
Data out
Arguments (parameters)
Return value
Program
input()
print()
Program
Program
Functions
Function style and documentation
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
"""
Program flow
Python Programs
Python Programs
Where does a Python program start?
Where does a Python program start?
def main():
print("Hello World!")
if __name__ == "__main__":
main()
https://realpython.com/python-main-function/
Program Flow
14
15
10
11
5
2
6
2
7
2
12
Order of execution
(by line #)
Scope
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"))
Function parameters and arguments
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])
Multiple returns