How can I write the below code, in a way that it only accepts names instead of integers or floats?
try:
name = input("What is your name?: ")
print("Your name is " +name)
except:
print("That isn't a valid name")
How can I write the below code, in a way that it only accepts names instead of integers or floats?
try:
name = input("What is your name?: ")
print("Your name is " +name)
except:
print("That isn't a valid name")
Here's an example using exceptions for checking whether given name could be a float or int, and looping until a valid name is given:
# Loop until break out
while True:
name = input("What is your name?: ")
try:
int(name)
print("An int is not a valid name")
# Go to start of loop
continue
except ValueError:
# Continue to next check
pass
try:
float(name)
print("A float is not a valid name")
# Go to start of loop
continue
except ValueError:
# Break loop if both exceptions are raised
break
print(f"Hello {name}!")
If you want to do it using try-except, an approach is to turn the input to an int or a float and then in the except print that the name is valid, like this:
try:
name = input("What is your name?: ")
test = float(name)
print("this is not a valid name")
except:
print("your name is " + name)
The problem is that the name can be 'foo2'
and it still works and to treat exceptions like that you need to write a lot of code.
As @JakobSchödl said just use name.isalpha()
which return true if the name contains anything that isn't a letter. Implementation below:
name = input("What is your name?: ")
if name.isalpha():
print("Your name is " +name)
else:
print("not a valid name")
This is much simpler.
You can also use a regex if you want but it's a bit more complicated, example below.
import re
match = re.match("[A-Z][a-z]+", name)
if match is not None:
print("your name is " + name)
else:
print("this is an invalid name")