首页 > 解决方案 > 结果重复

问题描述

大家好,所以我是新手,请在 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()    

标签: pythonloops

解决方案


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。


推荐阅读