How do I make an input() detect if the user input is something other than a string?

Question:

I am fairly new to Python and I wanted to generate a simple user input that asks for your name. I got the prompt to work but when I added code that detects if the input is not a string, it doesn’t let me input anything at all.

It was working up until I added the code that tells the user if they used an unsupported character.
Here’s the code I have so far:

while True:
  name = input('What is your name? ')
  if name is str:
    print('Hi,%s. ' % name)
  if name != str:
    print('That is not a valid character!')
Asked By: CalamityTerra

||

Answers:

Python supplies methods to check if a string contains on alphabets, alphanumeric or numeric.

isalpha() returns True for strings with only alphabets.

isalnum() returns True for strings with only alphabets and numbers and nothing else.

isdigit() returns True for strings with only numbers.

Also your if-else statement is off

name = input('What is your name? ')
if name.isalpha():
  print('Hi,%s. ' % name)
else:
  print('That is not a valid character!')
Answered By: surge10

When you do

name = input('What is your name? ')

you get a string called name, so checking it it is a string won’t work.

What you can check is if it’s an alphabetical character, using isalpha:

if name.isalpha():
    # as you were

There are various other string methods ( see here ) which start is to check for numbers, lower case, spaces and so on.

Answered By: doctorlove
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.