首页 > 解决方案 > 更多错误信息 + 更长的程序还是更少的错误信息 + 更短的程序?

问题描述

def question():
    original = input("Enter a word: ")
    if " " in original:
        print("\n**Please only enter one word.**")
        question()

    elif len(original) <= 0:
        print("\n**It seems as though you did not enter a word.**")
        question()

    elif not original.isalpha():
        print("\n**Please only use letters.**")
        question()

    else:
        print(original)

question()

VS。

def question():
    original = input("Enter a word: ")
    if len(original) > 0 and original.isalpha() and " " not in original:
        print(original)
    else:
        print("**Make sure you enter a word, only use letters, and only enter single word.**")
        question()

question()

这两个程序基本上是一回事。但是顶级程序更长,并且在用户输入无效响应时提供了更多关于出错的信息。底部程序要短得多,但没有为无效响应提供尽可能多的信息。在现实世界的编码中,就像在专业编程中一样,哪一个程序会比另一个程序更受欢迎?

标签: python

解决方案


除了少数例外(例如登录),更多的信息通常会更好(但这是高度主观的并且取决于具体情况)。话虽如此,我们可以稍微改进您的第一个详细选项,例如:

# Allow multiple, simultaneous errors
def question():
    while True:
        original = input("Enter a word: ")
        errors = []

        if " " in original:
            errors.append("\n**Please only enter one word.**")
        if len(original) <= 0:
            errors.append("\n**It seems as though you did not enter a word.**")
        if not original.isalpha():
            errors.append("\n**Please only use letters.**")
        # if <another test>:
        #     errors.append(<test message>)

        if not errors: break

        # If we get here, there were some errors -- print them and repeat
        print("".join(errors))

    # We've broken from the while loop, the input is good   
    print(original)

或者

# Don't allow multiple errors
def question():
    while True:
        original = input("Enter a word: ")
        err = None

        if " " in original:
            err = "\n**Please only enter one word.**"
        elif len(original) <= 0:
            err = "\n**It seems as though you did not enter a word.**"
        elif not original.isalpha():
            err = "\n**Please only use letters.**"
        # elif <another test>:
        #     err = <test message>

        if err is None: break

        # If we get here, there was an error -- print it and repeat
        print(err)

    # We've broken from the while loop, the input is good   
    print(original)

推荐阅读