我一直在尝试为在文本文件中输入新词的用户添加一些验证
输入必须仅由字母组成,并且我已使用带有.isalpha()
的if语句使其工作,但是我想尝试一下,看看是否可以使用try使其工作,但到目前为止我还没有使其工作
try语句允许所有输入,无论它是否包含数字或空格。我似乎看不出哪里出了问题
def AddNewWords():
List = []
Exit = False
while not Exit:
choice = input("Please enter a word to be added to the text file: ")
try:
choice.isalpha()
except:
print("Not a valid word")
continue
else:
List.append(choice)
Exit = True
Return List
AddNewWords()
没有
try
/except
子句,有很多方法可以实现您的结果。但是,引发手动异常是一种非常有效的方法,只需对代码进行几次更改即可应用首先,您需要确保
str.isalpha
的False
结果会引发错误:其次,应明确定义要捕获的异常:
完整解决方案:
你需要检查真/假,因为你不会得到任何异常,所以不要尝试“除非”。代码应该是
isalpha()
返回True/False,它不会引发任何异常请尝试以下方法:
FWIW,您还可以以更紧凑的方式重写循环,而无需使用exit变量,而是
while True
+break
:相关问题 更多 >
编程相关推荐