""" File: int_input.py Author: Mark Fienup with help from Intro. class Description: Implements a function int_input which validates an integer input. """ def int_input(prompt): """ Too simple since it does NOT allow for a sign (+,-) to preceed the digits""" while True: userInput = raw_input(prompt) if userInput.isdigit(): return int(userInput) else: print "ERROR: You can only enter digits" def int_input2(prompt): """ Code developed in class on 2-16-10""" while True: userInput = raw_input(prompt) userInput = userInput.strip() negSignPosition = userInput.find('-') if negSignPosition == 0: isNegative = True userInput = userInput[1:].strip() else: isNegative = False if userInput.startswith('+'): userInput = userInput[1:].strip() if userInput.isdigit(): if isNegative: return -1 * int(userInput) else: return int(userInput) else: print "ERROR: You can only enter a sign followed by digits" def int_input3(prompt): """ Slightly more readable verision of the class code""" while True: userInput = raw_input(prompt) userInput = userInput.strip() multiplier = +1 if len(userInput) == 0: print "ERROR: You can only enter a sign followed by digits:" continue elif userInput[0] == '+': userInput = userInput[1:] elif userInput[0] == '-': userInput = userInput[1:] multiplier = -1 userInput = userInput.strip() if userInput.isdigit(): return multiplier * int(userInput) else: print "ERROR: You can only enter a sign followed by digits" while True: x = int_input2("Enter an integer: ") print "Your integer was:",x