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.
Try using
ast.literal_eval
: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 usingif not x
as an additional validation. Use oftype
orisinstance
is inappropriate.In addition, you need to include
input
within yourwhile
loop so that a user is able to re-enter a name. Here's an example:"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.