0

I'm trying to modify the existing input function in a project just so that it can loop if the input given is not an integer, but I can't seem to find out how.

If this is a normal function it works:

def getInput():
    while True:
        try: x = int(input()); break
        except ValueError: print("Number not integer. Try again.")
    return x

numberOfNodes = getInput()

I've thought of changing this to def __input__(): but it does not modify the built-in function. Is there a way to re-write built-in functions? This piece of code is pretty much all I need but I was just curious to see if I can make it the default behavior for input.

  • 1
    You can try assigning `input = some_func` before defining the `getInput` function – Khanh Luong Oct 15 '22 at 03:42
  • @KhanhLuong Actually, just the opposite: `old_input=input`. And then you can redefine `input`. – DYZ Oct 15 '22 at 03:43
  • I would recommend not modifying the built-in function but just putting a very simple loop or defining another function there to solve the problem. However, not sure if that is also something you want. – Xin Cheng Oct 15 '22 at 03:44
  • You should *not* modify the built-in function; give your function a different name, ideally one that describes what it does (perhaps `int_input`). – kaya3 Oct 15 '22 at 03:54

1 Answers1

0

To summarize the discussion in the comments:

old_input = input

def input(*args):
  while True:
    try: 
      return int(old_input(*args))
    except ValueError: 
      print("Number not integer. Try again.")
DYZ
  • 55,249
  • 10
  • 64
  • 93