CIS 111 Functions and Flowcharts

Objectives

  • Read a hierarchy chart for an algorithm containing functions
  • Read a flowchart for an algorithm containing functions
  • Create a hierarchy chart for an algorithm containing functions
  • Create a flowchart for an algorithm containing functions

Overview

This page consists of examples of Python code along with some hierarchy charts and flowcharts. Many of the program examples for this page were previously presented in the course notes for functions. A more complex example is included at the end of this page to illustrate a slightly more complex hierarchy chart.

Add two numbers

Python Code

def add(n1, n2): sum = n1 + n2 return sum add(3, 4) # returns 7

Hierarchy chart

Flowchart

Add two numbers (with default values)

Python Code

def add(n1 = 10, n2 = 7): sum = n1 + n2 return sum add() # returns 17 add(3) # returns 10 add(3, 2) # returns 5

Hierarchy chart

Flowchart

Divide two numbers

Python Code

def divide(dividend, divisor): return dividend / divisor divide(10, 2) # returns 5.0 divide(dividend=10, divisor=2) # returns 5.0 divide(divisor=10, dividend=2) # returns 0.2

Hierarchy chart

Flowchart

Add up an unknown number of values

Python Code

def add(*n): sum = 0 for i in n: sum = sum + i return sum add(3, 5) # returns 8 add(3, 5, 10) # returns 18 add(3, 5, 10, -2) # returns 16

Hierarchy chart

Flowchart

Calculate area with input validation

Python Code

def isInt(s): """ Determines if the argument value represents an integer value """ try: i = int(s) if isinstance(s, str): return i == float(s) else: return int(s) == s except: return False def getInt(prompt="", min=float("-inf"), max=float("Inf")): valid = False while not valid: strIn = input(prompt) if isInt(strIn): num = int(strIn) if num < min: print("Error: Number entered is below minimum value of {0}".format(min)) elif num > max: print("Error: Number entered is above maximum value of {0}".format(max)) else: valid = True else: print("Error: Invalid integer") return num length = getInt("Enter the length (1-1000): ", 1, 1000) width = getInt("Enter the width (1-1000): ", 1, 1000) area = length * width print("The area of the rectangle is {0}".format(area))

Hierarchy chart