Skip to main content
 首页 » 编程设计

python之验证输入由字母字符组成

2024年09月07日11jirigala

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

输入必须仅由字母组成,我已经使用带有 .isalpha() 的 if 语句使它工作,但是我想尝试看看是否可以使用 try、except 和到目前为止我还没有让它工作。

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

请您参考如下方法:

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,您还可以在不使用退出变量的情况下以更紧凑的方式重写循环,而是使用 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")