1

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:

  1. How can i check/force user input? EX: repeating the input string or maybe even warning user that he didn't enter anything?

  2. 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

4

3 回答 3

2

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:

while True:
    answer = input('Enter something: ')
    if answer: break

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.

于 2012-11-22T06:48:14.743 回答
1

A reject all input unless of the correct type:

input_ = input('Enter some input: ')
try:
    input_ = int(input_) # or float(input_); str format is used with input() function by default
except ValueError: # can't convert
    pass # or some other friendly error message

To prevent empty inputs:

while True:
    input_ = input('Enter something: ')
    if input_: # if this value is not empty, for example None or ''
        break
pass # continue the program
于 2019-05-19T16:34:18.557 回答
0

To answer your second part of the question you can use the isinstance() function in python to check if a variable is of a certain type.

于 2012-11-23T00:39:49.190 回答