[Tutor] Re: Why can't I make this function work? (original) (raw)

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jul 16 19:28:58 CEST 2004


Thanks for the help, I've re-written the funcion as below and it seams to work correctly now.

def Getint(): "Function to collect a integer from the user" typecheck = 0 while typecheck == 0: try: integer = int(rawinput()) typecheck = 1 except: print "Invalid input, try agin. ", return integer

Hi Matt,

One nitpick: When we try interrupting a program by pressing Control-C, that actually raises a "KeyboardInterrupt" exception to make the program stop.

However, the loop above will disregard KeyboardInterrupts, so it'll make it difficult to interrupt that program in the middle of a Get_int(). I'd modify it just a little more so that the exception handling isn't so comprehensive:

try: integer = int(raw_input()) type_check = 1 except ValueError: ## <--- Changed line here print "Invalid input, try agin. ", ###

ValueError is the exception class that gets raised when we pass silly things to int():

int("foobar") Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): foobar ###

Hope this helps!



More information about the Tutor mailing list