如何为Python手动配置的LSAR聊天机器人正确添加错误提示?
问题分析与解决
核心问题
你的代码逻辑有两个致命问题:
- 多个
while语句是顺序执行的,比如第一个while只有当var等于"How are you?"时才会触发,执行完后var变成新输入,然后程序会跳到下一个while,只有新输入刚好匹配第二个while的条件才会执行,否则直接跳过,直到走到最后那个错误的循环。 - 最后一个
while的条件完全错误:你把var(字符串)和一个集合{"How are you?", ...}比较,字符串永远不可能等于集合,所以这个while的条件永远为True。一旦程序进入这个循环,不管你输入什么正确命令,都会一直触发错误提示,根本跳不出来。
修正后的代码
把所有逻辑放进一个主循环里,每次获取输入后判断匹配哪个命令,这样就能正常处理每一次输入,包括错误输入后再输入正确命令的情况:
# 初始化变量让循环启动 var = "" while True: var = input("\n请输入命令:\n") if var == "How are you?": print("im s0 g00d!! im just chilllin as usuallll ykn0w >_<") elif var == "What's your name?": print("im LSAR! nice t0 meet y0u friend :3") elif var == "CYN": print("[CALLBACK PING]") elif var == "Who are you?": print("It seems you have asked about LS's chat client auto-responder. This is an application designed to simulate LS's otherwise inimitable rad typing style, tone, cadence, personality, and substance of retort while he is unavailable. The algorithms are guaranteed to be 93 percent indistinguishable from LS's native neurological responses, based on some statistical analysis I basically just pulled out of my ass right now.") elif var == "What are you?": print("im n0t a what. be nice!! X(") else: print("ummmm wat. s0rry, idk what y0ure talllking ab0ut! X(\ntry an0ther c0mmand plllease, 0ne i understand this time ^_^")
逻辑说明
- 用
while True做无限循环,持续接收用户输入 - 每次输入后用
if-elif-else判断输入内容:- 匹配到对应命令就输出回复
- 没匹配到就输出错误提示
- 这样不管之前输入的是正确还是错误命令,下一次输入都会重新判断,不会陷入错误循环
内容的提问来源于stack exchange,提问作者artificialDeity
相关产品推荐
相关产品推荐

