如何在Python中判断变量匹配多个选项?校园辅助Bot代码求助
解决校园辅助机器人的多条件判断问题
嘿,我懂你想要实现的需求啦——让你的CareBot在用户输入指定的多个关键词(比如math或者其他你需要的学科词)时触发对应的逻辑对吧?这里有两种实用的方法来实现这个多条件判断:
方法一:使用in运算符(推荐,更简洁)
把所有需要匹配的关键词放到一个列表里,用in来检查用户输入是否在这个列表中。另外加上.lower()可以忽略大小写,不管用户输入Math、MATH还是math都能匹配成功,提升用户体验:
import time print('Hello, my name is CareBot and I am here to help!') time.sleep(3) name = input('Please input your name: ') print('Nice to meet you, %s. I am a bot that can lead you to resources to help out with school subjects!' % name) time.sleep(2) print('Now, what subject can I help you with?') helpselect = input('Please input a subject: ') # 替换成多条件判断 if helpselect.lower() in ['math', 'maths']: # 可添加更多关键词到列表中 print(f"Got it {name}! Here are some math learning resources for you...") # 在这里编写后续的资源引导逻辑
方法二:使用or连接多个条件
如果你的匹配关键词不多,也可以直接用or把多个相等判断连接起来,同样可以搭配.lower()处理大小写问题:
# 替换原有的if语句 if helpselect.lower() == 'math' or helpselect.lower() == 'maths': print(f"Got it {name}! Here are some math learning resources for you...") # 编写后续逻辑
小提示:你原来代码里的('*****')其实等价于'*****',括号是多余的,直接替换成上面的条件即可。
内容的提问来源于stack exchange,提问作者Graham Lewis
相关产品推荐
相关产品推荐

