How do i give a condition in which for example; if x is not an integer print("type an integer")
Asked
Active
Viewed 2,300 times
0

Moses Koledoye
- 77,341
- 8
- 133
- 139

ebere
- 55
- 1
- 10
2 Answers
0
With your sample code, your best bet is to catch the ValueError
and try again:
def get_int():
try:
return int(input('Type an integer:'))
except ValueError:
print("Not an int. Try again.")
return get_int()
The reason is because if the user enters a non-integer string, then the exception gets raised before you have a chance to check the type, so isinstance
doesn't really help you too much here.

mgilson
- 300,191
- 65
- 633
- 696
0
One way would be casting the value to into and handle the exception:
try:
parsed = int(user_input)
print ("int")
except:
print ("not int")

Ishay Peled
- 2,783
- 1
- 23
- 37