-1

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?

4 Answers4

2

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")
Hoopdady
  • 2,296
  • 3
  • 25
  • 40
1

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.

Olav
  • 547
  • 1
  • 5
  • 17
0

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
OdraEncoded
  • 3,064
  • 3
  • 20
  • 31
0

If you want to manage negative integers you should use :

value = ''
while not value.strip().lstrip("-").isdigit():
    value = input("Please enter the value")
mrlouhibi
  • 121
  • 4