Loop until an input is of a specific type

Question:

I’m trying to make a program that repeatedly asks an user for an input until the input is of a specific type. My code:

value = input("Please enter the value")

while isinstance(value, int) == False:
     print ("Invalid value.")
     value = input("Please enter the value")
     if isinstance(value, int) == True:
         break

Based on my understanding of python, the line

if isintance(value, int) == True
    break

should end the while loop if value is an integer, but it doesn’t.

My question is:
a) How would I make a code that would ask the user for an input, until the input is an integer?
b) Why doesn’t my code work?

Asked By: Mayur Mohan

||

Answers:

The reason your code doesn’t work is because input() will always return a string. Which will always cause isinstance(value, int) to always evaluate to False.

You probably want:

value = ''
while not value.strip().isdigit():
     value = input("Please enter the value")
Answered By: Hoopdady

input always returns a string, you have to convert it to int yourself.

Try this snippet:

while True:
    try:
        value = int(input("Please enter the value: "))
    except ValueError:
        print ("Invalid value.")
    else:
        break
Answered By: OdraEncoded

Be aware when using .isdigit(), it will return False on negative integers. So isinstance(value, int) is maybe a better choice.

I cannot comment on accepted answer because of low rep.

Answered By: Olav

If you want to manage negative integers you should use :

value = ''
while not value.strip().lstrip("-").isdigit():
    value = input("Please enter the value")
Answered By: mrlouhibi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.