'How can I use try and except to handle bad names?
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")
Solution 1:[1]
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}!")
Solution 2:[2]
The Problem Here With Try-Except
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.
Isalpha Function
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.
Using a Regex
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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | wjandrea |
