更多错误信息+较长程序,或更少错误信息+较短程序?

时间:2018-06-21 01:06:49

标签: python

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

这两个程序基本上是同一件事。但是顶层程序更长,并且可以提供有关用户输入无效响应时出了什么问题的更多信息。最底层的程序要短得多,但是对于无效响应,它给出的信息不多。在现实世界中的编码中(如在专业编程中一样),哪个程序比另一个程序更受青睐?

1 个答案:

答案 0 :(得分:0)

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

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