# recip.py # Lillian Lee (LJL2) and Steve Marschner (SRM2) # Apr 18, 2013 """Demonstrate use of try/except statements""" def recip1(x): """Return 1.0/x.""" return 1.0/x def recip2(x): """Return 1.0/x, or inf (infinity) if x is 0""" try: return 1.0/x except ZeroDivisionError: return float('Inf') def recip3(x): """Return 1.0/x, or inf (infinity) if x is 0""" # try this one with input 'Lee' or 'Marschner' if x != 0: return 1.0/x else: return float('Inf') def recip4(): """Solicit a number from user, and return its reciprocal. If the user enters invalid input, re-prompt""" prompt = "Pick a non-zero number, and I'll print out the reciprocal: " while True: try: x = float(raw_input(prompt)) return 1.0/x except ZeroDivisionError: print 'The number has to be NON-ZERO; please try again.' except ValueError: print 'The input has to be a NUMBER; please try again.' def recip5(): """Solicit a number from user, and return its reciprocal. If the user enters invalid input, re-prompt""" prompt = "Pick a non-zero number, and I'll print out the reciprocal: " goodinput = False # has a valid input been given yet? while not goodinput: x = raw_input(prompt) #PROBLEM - x is a string. # See is_float_literal below if not type(x) in [float, int]: print 'The input has to be a number; please try again.' elif x == 0: print 'The input has to be a number; please try again.' else: return 1.0/x def is_float_literal(s): """True if string s contains a valid float literal.""" has_digits = False i = 0 if s[i] in "-+": i += 1 while i < len(s) and s[i] in "0123456789": i += 1 has_digits = True if i < len(s) and s[i] == '.': i += 1 while i < len(s) and s[i] in "0123456789": i += 1 has_digits = True if i < len(s) and s[i] in "eE": i += 1 if i < len(s) and s[i] in "-+": i += 1 if i == len(s): return False while i < len(s) and s[i] in "0123456789": i += 1 return i == len(s) and has_digits assert is_float_literal("1") assert is_float_literal("10") assert is_float_literal("1.") assert is_float_literal(".1") assert is_float_literal("-.231") assert is_float_literal("1e10") assert is_float_literal("+1.0e10") assert is_float_literal("1.e10") assert is_float_literal(".1e10") assert is_float_literal(".1e+10") assert not is_float_literal("a") assert not is_float_literal(".") assert not is_float_literal("12e") assert not is_float_literal("12e+") assert not is_float_literal("e10") assert not is_float_literal(".e10")