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?
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")
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
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.
If you want to manage negative integers you should use :
value = ''
while not value.strip().lstrip("-").isdigit():
value = input("Please enter the value")
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?
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")
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
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.
If you want to manage negative integers you should use :
value = ''
while not value.strip().lstrip("-").isdigit():
value = input("Please enter the value")