Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 607
Troy Avatar asked Apr 09 '26 08:04

Troy


2 Answers

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
like image 181
Sercan Avatar answered Apr 12 '26 15:04

Sercan


You may use a while loop that only breaks when your input is within the given range:

def inputHour():
    while True:
        startHour = input("Starting time (hour, numbers only): ")
        if startHour.isdigit() and (0 <= int(startHour) <= 23):
            break
    return startHour
like image 44
Jan Avatar answered Apr 12 '26 17:04

Jan