Search code examples
pythonfunctiondry

Remove redundant lines in short input function


I'm trying to sanitize input for a 24-hour clock and the code below is what I came up with. A few lines are repeated and I would like to learn if there's a better pattern to avoid it.

def inputHour():
    startHour = input("Starting time (hour): ")
    while not startHour.isdigit():
        startHour = input("Please enter numbers only (0 - 23): ")
    while 0 < int(startHour) > 23:
        startHour = input("Invalid hour. Please enter value from 0 to 23: ")
        while not startHour.isdigit():
            startHour = input("Please enter numbers only (0 - 23): ")
    return startHour

Solution

  • In total you have 2 options; it is either not digit or not in desired range as integer. So, maybe you can merge them as below:

    def inputHour():
        startHour = input("Starting time (hour): ")
        while not startHour.isdigit() or 0 < int(startHour) > 23:
            startHour = input("Invalid input. Please enter numbers only (0 - 23): ")
        return startHour