pythonlistmembership

Is there a way I can check if any content of a list is within a variable, and then run a conditional?


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.")

Solution

  • 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: