Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

float(TimeHours) / 1 returns float. Did you mean float(TimeHours) // 1. And isinstance(TimeHours, str) can not be True as it is checked only if isinstance(TimeHours, int) is True. So it doesn’t ignore the if and elif, it just never enters them.

Side note:

isinstance(TimeHours, int) is True is redundant, just use isinstance(TimeHours, int) instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading