python - 结果重复
问题描述
大家好,所以我是新手,请在 python 中尝试循环,我不断重复我的结果,这是为什么?
cleanHello = 'you asked about clean hello'
greetings = 'hi'
def main():
while True:
try:
userInput = input('user: ')
for x in userInput:
if x in greetings:
print(cleanHello)
except(KeyboardInterrupt, EOFError, SystemExit):
break
main()
解决方案
for x in userInput:
if x in greetings:
...
您正在遍历输入中的每个字符并检查该单个字符是否在问候语或“hi”中。
您可能正在尝试这样做:
cleanHello = 'you asked about clean hello'
greetings = 'hi'
def main():
while True:
try:
userInput = input('user: ')
if greetings in userInput:
print(cleanHello)
except(KeyboardInterrupt, EOFError, SystemExit):
break
main()
如果你输入“say hi”,它会检查你输入的文本中是否有“hi”,然后打印 cleanHello。
推荐阅读
- reactjs - 使用 reactJS 制作推荐奖励系统
- java - 在杰克逊已经配置了原始超类型之后动态添加新的子类型
- ansible - 每个列表的第一项附加到 ansible playbook 中的另一个列表
- angular - 元标记未在 angular9 中更新(查看源代码)
- android - com.android.tools.r8.errors.a:仅从 Android O 开始支持 MethodHandle.invoke 和 MethodHandle.invokeExact
- wordpress - Next.js 可以在多站点模式下与 WordPress 一起使用吗?
- spring - 从实现 WebApplicationInitializer 的类访问 bean
- python - Scrapy登录,但不抓取任何东西
- python - 如何从二值图像中去除不必要的黑度(主要由暗区/噪声引起)
- sapui5 - SAPUI5 UploadCollection - 项目的哪个模板?