You can do it like this:
a = None
while type(a) != int:
try:
a = int(input())
except:
print("incorrect pick a number and try again")
print("Ok thanks you finally picked a number")
Essentially:
- Create a variable with
NoneType
so when you first run the program it can access the while loop because the conditions meats.
- Loop until the type of that variable is not
int
.
- Request the user input and try to cast as integer, if it fails print an error and try again.
- When the input is of integer type it exit the loop and print the final message.
You can use type()
or isinstance()
to check, but as suggested by @chepner avoid the usage of type
because it simply returns the type of an object whereas, isinstance()
returns true
if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.
To help you understand:
class foo:
pass
class bar(foo):
pass
isinstance(foo(), foo) # returns True
type(foo()) == foo # returns True
isinstance(bar(), foo) # returns True
type(bar()) == foo # returns False,and this probably won't be what you want.
In the case you want to use isinstance()
the code will result as:
a = None
while not isinstance(a, int):
try:
a = int(input())
except:
print("incorrect pick a number and try again")
print("Ok thanks you finally picked a number")
As pointed out by @L3viathan you can also do:
a = None
while a is None:
try:
a = int(input())
except:
print("incorrect pick a number and try again")
print("Ok thanks you finally picked a number")
In this case you loop until a
get a value, that will be done only if the exception is not thrown.