Home > OS >  While loop skipping If conditional when using isinstance [duplicate]
While loop skipping If conditional when using isinstance [duplicate]

Time:10-03

I want a while loop to store an input in a variable and check if it is an integer or a float before printing a statement and breaking the loop. If the variable fails the check I want it to continue back to the top of the loop and ask for the input again until it gets a valid response.

Somehow regardless of what the input is, the loop asks for an input again and seems to skip the if conditional block.

def FeelingCalc():

    Monday = 0

    while Monday == 0:
        Monday = input("On a scale of 1 to 10, how did you feel on Monday? ")
        if isinstance(Monday,(int,float)) and 11 > float(Monday) > 0:
            print("Alright. Let's move on.")
            break
        else:
            print("Please type a whole number between 1 and 10.")
            Monday = 0
            continue

I have tried different solutions for the if conditional like:

if Monday != type(int)

but that doesn't seem to do anything either. It still goes to the else block.

CodePudding user response:

You always get string when you use input. So, you have to convert Monday to an integer or float.

Monday = int(input("On a scale of 1 to 10, how did you feel on Monday? "))

EDIT

You might want to use try block:

try:
   Monday = float(input("On a scale of 1 to 10, how did you feel on Monday?"))
except: 
   Monday = 0

CodePudding user response:

The problem is here:

if isinstance(Monday,(int,float)) and 11 > float(Monday) > 0:

Since Monday is derived from input() it will always be a string. If it wasn't a string, but an int or float, there would be no need to cast it to float. You probably want something like this:

try:
    x = float(input())
except:
    print("Please enter a number ")

if x > 11 or x < 0:
    print("Number must be in range 1-10")

EDIT if you don't want anything except int (as the other answers assume), replace float with int.

  • Related