如何使用try-and-except来处理坏名字



如何编写下面的代码,使其只接受名称而不接受整数或浮点值?

try:
name = input("What is your name?: ")
print("Your name is " +name)
except:
print("That isn't a valid name")

以下是一个使用异常检查给定名称是否可以是float或int并循环直到给定有效名称的示例:

# 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}!")

Try Except的问题

如果你想使用try-except,一种方法是将输入转换为int或float,然后在except打印中表明名称有效,如下所示:

try:
name = input("What is your name?: ")
test = float(name)
print("this is not a valid name")
except:
print("your name is " + name)

问题是名称可以是'foo2',但它仍然有效,要像这样处理异常,需要编写大量代码。

Isalpha函数

正如@JakobSchödl所说,只要使用name.isalpha(),如果名称包含任何非字母的内容,就会返回true。以下实施:

name = input("What is your name?: ")
if name.isalpha():
print("Your name is " +name)
else:
print("not a valid name")

这要简单得多。


使用Regex

如果需要,您也可以使用正则表达式,但它有点复杂,例如下面的示例。

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")

最新更新