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.
解决方案
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