如何在python中重置输入

时间:2016-10-13 19:39:31

标签: python

所以我有这个代码基本上由你提问题,但我有它所以输入回答问题,所以你只能问一个问题,然后你必须一次又一次地重置整个事情,我有它先问你的名字,所以我想要一个忽略它的循环。

    print("hello,what is your name?")
name = input()
print("hello",name)

while True:
    question = input("ask me anything:")
    if question == ("what is love"):
        print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name)
        break
    if question == ("i want a dog"):
        print("ask your mother, she knows what to do",name)
        break
    if question == ("what is my name"):
        print("your name is",name)
        break

3 个答案:

答案 0 :(得分:3)

摆脱break,以便循环不断提示新问题。为了提高性能,请将后续的if测试更改为elif测试(不是绝对必要的,但如果您在早期获得命中,则可以避免重新检查字符串):

while True:
    question = input("ask me anything:")
    if question == "what is love":
        print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name)
    elif question == "i want a dog":
        print("ask your mother, she knows what to do",name)
    elif question == "what is my name":
        print("your name is",name)

当然,在这种特定情况下,您可以通过使用dict执行查找来避免重复测试,无需重复测试即可进行任意数量的提示:

# Defined once up front
question_map = {
        'what is love': "love is a emotion that makes me uneasy, i'm a inteligence not a human",
        'i want a dog': 'ask your mother, she knows what to do',
        'what is my name': 'your name is',
        # Put as many more mappings as you want, code below doesn't change
        # and performance remains similar even for a million+ mappings
    }

print("hello,what is your name?")
name = input()
print("hello",name)

while True:
    question = input("ask me anything:")
    try:
        print(question_map[question], name)
    except KeyError:
        # Or check for "quit"/break the loop/alert to unrecognized question/etc.
        pass

答案 1 :(得分:0)

print("hello,what is your name?")
name = input()
print("hello",name)

while True:
    question = input("ask me anything:")
    if question == ("what is love"):
        print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name)
    elif question == ("i want a dog"):
        print("ask your mother, she knows what to do",name)
    elif question == ("what is my name"):
        print("your name is",name)

答案 2 :(得分:-1)

取出break。然后使用break

将其中一个选项“退出”