-1

I'm trying to create a function that validates user input using exceptions.

def int_input(message):
while True:
    try:
        x=int(input(f'{message}: '))
        return x
        break
    except:
        print("Enter a valid integer!")
        print()
        continue

a=int_input("Enter num: ") print(a)

The code looks messed up, is there a better way to write this?

  • 1
    you could use `str.isnumeric` to check. I’d try to avoid exceptions in general because it’s kinda expensive to keep raising them, but as you’re just validating user input I don’t think the perf aspect matters that much here. – rv.kvetch Jan 15 '22 at 16:08
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Matthias Jan 15 '22 at 16:14
  • Using exceptions in Python is pretty standard ([Idiomatic Python: EAFP versus LBYL](https://devblogs.microsoft.com/python/idiomatic-python-eafp-versus-lbyl/)). Of course here you don't need `break` because you return before you reach that line and you don't need `continue` because the loop will continue anyway. – Matthias Jan 15 '22 at 16:17

1 Answers1

0

I think this may help you!

def int_input():
    while True:
        try:
            input_ = int(input("int: "))
            return input_
        except ValueError:
            print("Enter a valid integer!")
int_input()
amd
  • 342
  • 1
  • 2
  • 15