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!')
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!')
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.
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!')
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!')
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.