Python program that checks wether an input has an

2019-07-15 15:14发布

问题:

So I'm trying to make a program here that asks for an input but then checks whether the input has an integer, boolean or float and if it has any of these characters then it will ask for the input again. I want to do that instead of just writing str(input()) as if the user inputs an int or bool etc it will print error and stop the program.

Here is what I have at the moment but it isn't working:

x=input('Enter your name: ')
while True:
    if x==int or x==bool or x==float:
       print('error, incorrect name please try again!')
    else:
       print('Nice name', x, '!')
       break

If you can help please reply.

回答1:

It seems you want to check your name only includes alphanumeric characters and potentially whitespace. You can achieve this via str.isalpha after splitting by whitespace.

Remember that input always returns a string, so you need to use string methods to validate user input. You can check for empty strings using if not x as an additional validation. Use of type or isinstance is inappropriate.

In addition, you need to include input within your while loop so that a user is able to re-enter a name. Here's an example:

while True:
    x = input('Enter your name: ')
    if (not x) or (not all(i.isalpha() for i in x.split())):
        print('Error, incorrect name please try again!')
    else:
        print('Nice name', x, '!')
        break


回答2:

"checks whether the input has an integer, boolean or float" doesn't really mean anything. input always returns a string, and a string doesn't "have an integer boolean or float", it only has characters, period. You have to rethink and reword your specifications on what is an acceptable input based on this fact (which sets / sequences of characters are allowed or disallowed), and only then will you be able to write the proper validation code.



回答3:

Try using ast.literal_eval:

import ast
x = input('Enter your name: ')
try:
   if type(ast.literal_eval(x)) in (bool,float,int):
      print('Error, incorrect name please try again!')

except:
   print('Nice name', x, '!')