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

Alan Gauld alan.gauld at blueyonder.co.uk
Mon Jul 19 23:47:51 CEST 2004


def Getint(): "Function to collect an integer from the user" typecheck = 0 while typecheck == 0: int = rawinput() if type(int) != type(1): print "Invalid input" else: typecheck = 1 return int

Its usually a bad idea to use a Python builtin name as a variable. int is the function for converting to an integer. Thisis particularly unfortunate here because you need it to convert your raw_input string to an integer! - Thats why the type test keeps failing....

However a more Pythonic way to do this is probably via an exception:

def getInt(): while True: try: num = int(raw_input()) except TypeError: continue return num

That will of course work for floats (which will be converted to ints, so it might not be exactly what you want. But a simple test before the conversion would fix that.

def getInt(): while True: try: num = raw_input() if '.' in num: continue else num = int(num) except TypeError: continue return num

HTH,

Alan G.



More information about the Tutor mailing list