首页 > 解决方案 > 初学者输入验证问题

问题描述

编写一个程序,提示用户输入一系列单词。然后程序会显示唯一单词列表(仅出现一次的单词,即不重复)。

我试过摆脱输入验证,但是如果用户输入任何值。程序中断。

list5 = []
game_over = False

while game_over is False:
    user_input = input("Please enter a word: ")
    list5.append(user_input)
    keep_it_going = input("Would you like to enter more words? (Y / N): ")
    while len(keep_it_going) != 1 and keep_it_going.lower() != "y" or "n":
        print("You entered an invalid value, please try again!")
        keep_it_going = input("Would you like to enter more words? (Y / N): ")
    if keep_it_going.lower() == "y":
        continue
    elif keep_it_going == "n":
        game_over = True

我希望程序能够运行,因为我没有看到任何逻辑失误,但是一旦我为“你想输入更多单词吗?(Y/N):”输入值“Y”,程序就会告诉我“输入了无效值。

标签: python

解决方案


while len(keep_it_going) != 1 and keep_it_going.lower() != "y" or "n":

是你的问题。它既不是“y”也不是“n”是错误输入,因此您需要将其更改为以下内容:

while len(keep_it_going) != 1 or keep_it_going.lower() != "y" and keep_it_going.lower() != "n":

推荐阅读