繁体   English   中英

我如何重置python中的输入

[英]how do I reset a input in 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

去掉break s,这样循环就会不断提示新问题。 为了提高性能,将随后的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
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)

取出break s。 然后有一个选项是“退出” break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM