python - 初学者输入验证问题
问题描述
编写一个程序,提示用户输入一系列单词。然后程序会显示唯一单词列表(仅出现一次的单词,即不重复)。
我试过摆脱输入验证,但是如果用户输入任何值。程序中断。
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”,程序就会告诉我“输入了无效值。
解决方案
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":
推荐阅读
- sql-server - 当我在 SQL Server 中进行分组时,如何跳过只有一个条目的 max 函数
- html - 如何在减少 text_field 宽度的同时将表单列中的 text_field 中心与同一行中的按钮对齐?
- c# - Linq 查询以限制分组
- java - 检查 LogCat 是否已经在运行
- django - 重置密码功能
- php - 将 CURL 命令转换为 CURL php
- reactjs - React 路由器 - 如何摆脱 url 中的 #
- javascript - 在 JavaScript 前端应用程序中共享通用库
- javascript - 为什么当用户将鼠标悬停在图像上时图像不会改变?
- nginx - Nginx 处于活动状态但重新启动 php7.2-fpm nginx 仍然失败