I have some functions calling for user input, sometimes string, int or whatever. so i noticed that if ENTER is pressed with NO INPUT i get an error. SO i did some research and i think i found that EVAL function may be what I’m looking for, but then again i read about its dangers.
SO here are my questions:
-
How can i check/force user input? EX: repeating the input string or maybe even warning user that he didn’t enter anything?
-
how do i check for the correct type of input (int, float, string, etc) against whatever the user types without having my scripts returning errors?
I appreciate your feedback,
Cheers
For question 1: enter pressed when prompted for input results in an empty string returned (are you using input() in your scripts?). Apparently empty string is not a valid input for your functions. For all I know, whatever you enter as the input, you end up with a string returned by input(). To check if a string is empty and repeat the prompt, you may try:
And for question 2: for checking the type of argument provided, generally the Pythonic way is to handle it with try/except and not check explicitly for each valid/non-valid type. Also, in this scenario you have to do explicit manual conversion from string, so you only check the contents of the string, not deal with other types (at least not yet). Because of than, you might be interested in string methods or re (regular expressions) module for checking if some particular substring is present (or not).
re module for python3.3 and
string methods for python3.3
For other versions of python, just select an appropriate value in the menu in the top of the page.