验证输入是否由字母字符组成

2024-10-03 00:29:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试为在文本文件中输入新词的用户添加一些验证

输入必须仅由字母组成,并且我已使用带有.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()

Tags: to用户if字母exit数字语句list
3条回答

没有try/except子句,有很多方法可以实现您的结果。但是,引发手动异常是一种非常有效的方法,只需对代码进行几次更改即可应用

首先,您需要确保str.isalphaFalse结果会引发错误:

if not choice.isalpha():
    raise ValueError

其次,应明确定义要捕获的异常:

except ValueError:
    print("Not a valid word")
    continue

完整解决方案:

def AddNewWords():
    L = []
    Exit = False
    while not Exit:
        choice = input("Please enter a word to be added to the text file: ")
        try:
            if not choice.isalpha():
                raise ValueError
        except ValueError:
            print("Not a valid word")
            continue
        else:
            L.append(choice)
            Exit = True
    return L

AddNewWords()

你需要检查真/假,因为你不会得到任何异常,所以不要尝试“除非”。代码应该是

def AddNewWords():
    List = []
    Exit = False
    while not Exit:
        choice = input("Please enter a word to be added to the text file: ")
        if not choice.isalpha():
            print("Not a valid word")
            continue
        else:
            List.append(choice)
            Exit = True
    return List

AddNewWords()

isalpha()返回True/False,它不会引发任何异常

请尝试以下方法:

choice = input("Please enter a word to be added to the text file: ")
if not choice.isalpha():
    print("Not a valid word")
    continue
List.append(choice)
Exit = True

FWIW,您还可以以更紧凑的方式重写循环,而无需使用exit变量,而是while True+break

while True:
    choice = input("Please enter a word to be added to the text file: ")
    if choice.isalpha():
        List.append(choice)
        break
    print("Not a valid word")

相关问题 更多 >