[Tutor] Re: Why can't I make this function work?

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 Get_int():
>     "Function to collect a integer from the user"
>     type_check = 0
>     while type_check == 0:
>         try:
>             integer = int(raw_input())
> 	    type_check = 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

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

    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 "<stdin>", line 1, in ?
ValueError: invalid literal for int(): foobar

Hope this helps!

More information about the Tutor mailing list