I`m trying to make a try-parse in Python 3. And it workes as it should (if I enter an int it return what I entered and if I enter a string it gives an error) but I would like to return a message to the user insted of getting the error message from the computer if I enter a string instead of int. For exemple print("Error! Please enter a number") and then give the user the chance to try again. Anyone who have a tip on how I could do?

def try_parse_int(text):
  try:
    return int(text)
  except:
    return None

Thank you in advance!

1

There are 1 best solutions below

2
Loïc On

You can easily do that by having the function call itself recursively :

def get_int():
  print('Please, enter a number:')
  val = input('=> ')
  try:
    return int(val)
  except ValueError:
    print("Error, that isn't a number!")
    return get_int()