Loop Until An Input Is Of A Specific Type
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(val
Solution 1:
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 = ''whilenot value.strip().isdigit():
value = input("Please enter the value")
Solution 2:
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.
Solution 3:
input
always returns a string, you have to convert it to int
yourself.
Try this snippet:
whileTrue:
try:
value = int(input("Please enter the value: "))
except ValueError:
print ("Invalid value.")
else:
break
Solution 4:
If you want to manage negative integers you should use :
value = ''whilenot value.strip().lstrip("-").isdigit():
value = input("Please enter the value")
Post a Comment for "Loop Until An Input Is Of A Specific Type"