In Python, I have code where I only want the input to be a number and I want there to be an error message if the user inputs a string(words). How do I do that?
Asked
Active
Viewed 1,311 times
-2
-
Do you want to prompt the user to try again if they give bad input? – PM 2Ring Sep 19 '18 at 23:56
-
Yes that would be great – user10388427 Sep 20 '18 at 00:05
-
Ok. Kevin's answer in the linked question shows you exactly how to do that. ;) – PM 2Ring Sep 20 '18 at 00:10
-
It would be great if you append a code stub of what you did for solving your question. With a sample code, your question will be viewed by more users. – Hamid Rouhani Sep 20 '18 at 00:19
2 Answers
1
use try and except
userInp = input("YOUR QUESTIONS")
try:
float(userInp)
except ValueError:
print("YOUR ERROR")
0
You can have the input inside a while loop. In the loop you can check the type of the input (make sure to assign it to a variable). Have a condition that exits the loop when the input is a number and give an error message when it is not

markb
- 281
- 2
- 8