在 python 中限制和验证输入

Limiting and Validating inputs in python

我试图限制我输入的字符长度,然后验证它是否是三个白色字符之一。努力完成最后一部分:

while True:
    try:
        letter=input("Please enter a character: ") #most intuitive way for me was the assert function but very happy to hear any other ways
        assert len(letter) !=1
    except AssertionError:
        print("Please type only ONE character")
    else:
        whitespace=["\n"," ","\t"] #i believe the list specification here makes the not in code invalid? believe the two may not be compatible but errors not reached there yet
        if whitespace not in letter:
            print("Your character in lower case is: "+str(letter).lower())
        else:
            print("You typed a white space character!")

欢迎使用 Whosebug!

看起来错误在 if whitespace not in letter: 行。这实际上应该是相反的:if item not in list:。您有 if list not in item:.

此外,如果我稍微重新格式化一下您的代码,它可能会对您有所帮助。

while True:
    letter = input('Please enter a character: ')

    if len(letter) != 1:
        print('Please type only ONE character')
        continue

    if letter in ['\n', ' ', '\t']:
        print("You typed a white space character!")
        continue

    lowercase_letter = letter.lower()
    print(f'Your character in lower case is: {lowercase_letter}')

如果您还没有看过 pylint,我建议您看一看。它可以帮助您将代码格式化为 PEP8 标准。它还能很好地指出代码中的一些简单错误。

引发异常用于向调用函数报告错误 - 即您无法执行该函数应该执行的工作,因为输入或系统状态不符合该函数的要求。

捕获异常用于处理您知道如何在更高级别的函数中处理的特定错误。因此,例如,如果您尝试读取一个文件但它不存在。在您的程序中,这意味着用户尚未在配置文件中设置特定标志...因此您可以捕获该异常并让用户知道如何解决该问题。

引发 Exception 并在同一函数中捕获它(至少在这种情况下)只是编写 if 语句的一种非常复杂的方式。

在编写 if-else 语句时,尝试使 if 分支为正是个好主意。这意味着如果可以,请避免 if not ...: else:

在您的代码中,letter 已经是一个字符串对象 - 因此无需使用 str(letter) 创建新的字符串对象。在 python 中,一切都是对象,即使是文字。

continue 语句跳转到循环的下一次迭代。在循环的当前迭代中执行 continue 之后的任何内容。您还可以查看完成循环执行的 break 语句。作为练习,您可以考虑在代码中添加额外的检查以查看用户是否键入了 'quit',然后是 break。你认为会发生什么?

if letter.lower() == 'quit':
    break

这必须在检查单个字母之前添加,否则您将永远无法进行此检查。

最后,不要在打印语句中使用字符串连接(使用 str + str)。您可以使用 f-strings,如示例 f'Hi my name is {name} and I am from {home}' 中的格式字符串,其中 namehome 是字符串变量。

希望对您有所帮助!

我建议您不要使用异常,因为它们非常不稳定。相反,我会使用 if/else 条件,例如:

    letter = input('Please enter a character: ')
    if len(letter) == 1:
        if letter in '\n\t ':
            print('You typed a white space character!')
        else:
            print('Your character in lowercase is {}'.format(letter.lower()))
    else:
        print('Please type only ONE character')```