CIS 111 Modules

Objectives

  • Create a Python module
  • Use functions from Python modules

Overview

Creating Python modules is easy. All you need to do is create a Python program and save it with a .py extension. You can then use data and functions from that module by using the import statement. You've been creating Python modules without even knowing it. You've also been using Python modules from its standard library. Now it is time to combine those two skills.

The module (myinput.py)

We need a module to experiment with. One good place to start is with some nice input validation functions. Here is an example you shoud save as myinput.py: 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 isFloat(s): """ Determines if the argument value represents a float value """ try: i = float(s) return True 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 def getFloat(prompt="", min=float("-inf"), max=float("Inf")): valid = False while not valid: strIn = input(prompt) if isFloat(strIn): num = float(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 number") return num

Importing the myinput.py module in general

import myinput print(myinput.getInt("Enter your age: ", 0, 130)) print(myinput.getFloat("Enter your hourly rate: ", 9.50))

Importing specific functions from the myinput.py module

from myinput import getInt, getFloat print(getInt("Enter your age: ", 0, 130)) print(getFloat("Enter your hourly rate: ", 9.50))