0

This code would perform error handling if the input was, "Type a number".

while True:
  try:
    a = int(input("Type a number."))
  except ValueError: #etc. with "float(input" and stuff. But you know that.
    print("That is an invalid input. Try again.")
    continue
  else:
    break

And etc, etc.

But how would I perform error handling to check if something is in the format, for example, let's try to check whether or not the input is in the format <single letter **************> </> <number ******************> (the * and spaces are just so that the phrase I type won't disappear)? As an example to the format, something like f/16.

The code which I presume should be correct is something similar to the above code, just replacing ValueError with something. However, if I am wrong, what is it meant to be?

Vishesh Mangla
  • 664
  • 9
  • 20
DasGuyDatSucks
  • 103
  • 1
  • 11

1 Answers1

1

regular expressions are useful for input validation, you could try sth like this:

import re
while True:
  try:
    a = input("type something: ")
    if not re.match(r'[a-zA-Z]/\d+', a):
        raise ValueError("invalid input ({}). value must be <letter>/<number>.".format(a))
    # ...add some more tests here if necessary, e.g. 0 <= number <= 100
    a = int(a.split('/')[1])
    if a < 0 or a > 100:
        raise ValueError("invalid input({}). number must be in interval [0,100].".format(a))
    # leave the loop if all checks pass...
    break
  except ValueError as e:
      print(str(e))
mrxra
  • 852
  • 1
  • 6
  • 9