Apr-08-2017, 08:34 PM
Why does the call of inclusive_range() at line 71 not throw an exception and instead it prints "Test FAILED"?
def test(*args): print(type(args)) print(len(args)) if len(args) == 1: raise ValueError("too many args, [1, 2]") def inclusive_range(*args): numargs = len(args) print(numargs) if numargs < 1: raise ValueError("number of args less than 1, needed interval [1, 3]") elif numargs == 1: start = 0 stop = args[0] step = 1 elif numargs == 2: (start, stop) = args step = 1 elif numargs == 3: (start, stop, step) = args else: raise ValueError("number of args greater than 3, needed interval [1, 3]") i = start while i <= stop: yield i i += step # test cases def main(): # valid 1 arg for i in inclusive_range(20): print(i, end=' ') print() # valid 2 args for i in inclusive_range(0, 21): print(i, end=' ') print() # valid 3 args for i in inclusive_range(0, 22, 2): print(i, end=' ') print() # invalid 0 args try: myRange = inclusive_range() for i in myRange: print(i) except ValueError as e: print(e) except: print("Unknown exception occured") else: print("Test FAILED") # invalid 4 args try: myRange = inclusive_range(1, 2, 3, 4) for i in myRange: print(i) except ValueError as e: print(e) except: print("Unknown exception occured") else: print("Test FAILED") # invalid 5 args, warning myRange not used (possibly optimized out by python) try: myRange = inclusive_range(1, 2, 3, 4, 5) except ValueError as e: print(e) except: print("Unknown exception occured") else: print("Test FAILED") test() try: test(1) except ValueError as e: print(e) else: print("everything is fine here, move along.") if __name__ == "__main__": main()