I want to ask the user to input only integer, later which will be stored in a variable. If user enters a string input, then prompt user to enter a valid integer,string is not allowed. Thanks
Asked
Active
Viewed 278 times
-3
-
Possible duplicate of [How can I read inputs as integers in Python?](http://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-integers-in-python) – miradulo Apr 12 '16 at 13:04
-
I allready read this post, but in my case I want my program to process only when an integer value is asigned to my_variable.,, if not ask again, and again until int is asigned – Hardi Apr 12 '16 at 13:08
-
@Hardi Welcome aboard! :) People typically post their own attempts at fixing the issue when asking a question; it shows effort and makes it much easier to give good advice. Try searching google or this site for "get variable type python", "integer check python" or read the answers to [this question](https://stackoverflow.com/questions/402504/how-to-determine-the-variable-type-in-python). If the whole thing blows up, post your faulty code and everybody will be more than happy to help! – jDo Apr 12 '16 at 13:32
-
Will do, thanks for your advice,, – Hardi Apr 12 '16 at 13:34
2 Answers
0
a=input()
try:
int(a)
print("Valid")
except:
print("Invalid")
Try and except are used in error handling. I am taking an input and I am trying to convert it into an integer. If an alphabet or special character is given then an error arises in converting the string to an integer and the program follows the order given in the except() part and prints Invalid.

Code Carbonate
- 640
- 10
- 18
-2
try this
response = ''
while not isinstance(response, int):
try:
response = int(raw_input('MSG :'))
except:
print 'Not int'
continue

guest
- 14
-
Maybe someone down-voted your answer because OP seems to be using Python3.x. Your code would probably run fine in Python2.x but in Python3.x `print variable` was changed to `print(variable)` and `raw_input()` was replaced by `input()`. – jDo Apr 12 '16 at 13:40
-
I downvoted, because I don't find "try this" answers on "do my code for me" questions particularly useful to anyone. – miradulo Apr 12 '16 at 13:42
-
@DonkeyKong Ah, I get that (but (at)guest might not unless you leave a comment). – jDo Apr 12 '16 at 13:56