【问题标题】:Validating a quiz in python such that the only valid inputs for retaking the quiz are 'y' or 'n'?在 python 中验证测验,以便重新参加测验的唯一有效输入是“y”或“n”?
【发布时间】:2018-11-05 22:28:43
【问题描述】:

我正在使用 Python 3.1.3,我正在尝试编写一个测验来测试我自己对元素周期表中元素名称和相应原子序数的了解,使用随机数生成器来选择是否询问用户原子序数或元素名称以及要询问的元素。 我目前正在尝试验证所有用户输入。我已经成功验证了数字和字母输入,但我正在努力验证重新参加测验的“是”或“否”选项,接受输入:“y”或“n”。 我之前曾尝试使用几个 IF 和 ELIF 语句来确定用户是否给出了等于有效输入的输入,但是在搜索堆栈溢出后,我将代码更改为如下所示:

##Functions
def validating_y_or_n_only(a,b,c):
    while b == 0:
        if not a:
            print("\n\tYou didnt enter anything.")
        elif a in ["y","n"]:
            b = 1
        else :
            print("\n\tYour input was invalid.")
        print("\tOnly 'y' and 'n' are considered valid.\n")
        print(c)
        a = str(input("\tEnter 'y' for yes or 'n' for no: "))
    return a

##Main Program
retake = "\n\tWould you like to re-take the quiz?"
print(retake)
replay_option = str(input("\tEnter 'y' for yes or 'n' for no: "))
replay_option = validating_y_or_n_only(replay_option,condition,retake)

但是,这会创建一个无限循环,甚至“y”或“n”的有效输入或不被接受。

【问题讨论】:

    标签: python python-3.x validation input while-loop


    【解决方案1】:

    您的逻辑似乎过于复杂。有许多变量似乎是不必要的或未使用的。使用有意义的名称而不是 abc 也是一种很好的做法。

    这是一种解决方案,它在while 循环中使用break 来指示何时输入了有效数据。

    def validating_y_or_n_only():
        while True:
            answer = str(input("\tEnter 'y' for yes or 'n' for no: "))
            if answer in ('y', 'n'):
                break
            elif not answer:
                print('\n\tYou didnt enter anything.')
            else:
                print('\n\tYour input was invalid.')
                print('\tOnly "y" and "n" are considered valid.\n')
        return answer
    
    replay_option = validating_y_or_n_only()
    

    【讨论】:

    • 感谢代码,但是我对 python 了解不多,想知道你给出的第一个 IF 语句是使用元组还是列表,或者结果是否存在差异实例。另外,“真”条件有什么作用?
    • 这里有两个单独的问题:(1) 您可以使用`tuple, set, or list. In this context, in`将与{'y', 'n'}, ['y', 'n'], ('y', 'n')中的任何一个一起使用。 (2) while True 表示继续循环,直到到达break
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多