0

I just recently started messing around with coding, and I'm currently working on a timer. It works fine for the most part, but the issue I'm having is that I'm trying to set a condition for if the user were to put in characters that aren't numbers into the input for hours, minutes, or seconds. Is there a way that I can make a list with each character that's not a number being its own item in the list, and then if any item from the list appears within the inputs for hours, minutes, or seconds, it displays in error message? I've tried something like this, but it didn't work.

sec_ = input("Seconds: ")

list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", 
        "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

if list[0:27] in sec_:
    
    print("You need to input a number.")
mozway
  • 194,879
  • 13
  • 39
  • 75
moud
  • 13
  • 3
  • I guess you want to do the opposite: `if sec_ in letters_list:` (do not name variables `list`, this is a python builtin), the best however remains to try converting to `int` and `try/except` the error – mozway Dec 03 '21 at 13:37
  • It's a lot easier to test for what you *want* than to try to blacklist *everything else*. In this case you'd just want to try to convert the input into a number, and if that raises an error, tell the user their input was invalid. – deceze Dec 03 '21 at 13:39

1 Answers1

0

You can handle the exception like follow:

try:
  sec_ = int(sec_)
except:
  raise ValueError("Error to be displayed")

If sec_ is a string you'll get your exception, if is something that can be converted into an integer, then it'll work.

Some reference: