Skip to content
Advertisement

While loop not taking ‘if’ statement into account

I’m trying to write a program in Python where the user is asked to input a number of hours after which a countdown starts in seconds, however I want to also make sure that no floats/strings are inputted and if they are, the user needs to be prompted with the same question and input a correct value. If an integer is inputted then I want the program to jump to the next statement (hence ‘pass’ on line 4). However, whatever I type in, the program always jumps to the next statement, regardless of whether it’s a string or a float.

TimeHours = input("Countdown time in hours:")

while isinstance(TimeHours, int) is True:
    pass
    if float(TimeHours) / 1 != int(float(TimeHours)):
        input('Please input a whole number, decimals are not accepted.')
    elif isinstance(TimeHours, str):
            input('Alphabetical letters or unknown characters are not allowed, e.g. A, B, C, (, *')
            continue

I tried using if statements and defining functions, but I can’t seem to make it work.

Advertisement

Answer

like this

while True:
    TimeHours = input("Countdown time in hours:")
    try:
        TimeHours = int(TimeHours)
        break
    except ValueError as e:
        print('Alphabetical letters or unknown characters are not allowed, e.g. A, B, C, (, *')
        continue
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement