2016-10-13 3 views
-3

그래서 기본적으로 당신이 질문을 구성하는이 코드를 가지고 있지만 입력 된 질문에 대한 답변을하므로 질문 하나만을 물을 수 있습니다. 그러면 전체를 다시 설정해야합니다. 다시는 또 다시, 나는 당신에게 당신의 이름을 먼저 물으려고합니다. 그래서 그것을 무시하는 루프를 원합니다.어떻게 파이썬에서 입력을 재설정합니까

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 
+5

당신은'break' 문 치우는 시도 했습니까? 아마도 exit 조건을 추가하고 싶을 것입니다 (예 :'question == ("Quit") 인 경우) : break' – nbryans

+0

[How to ask] (http://stackoverflow.com/help/how-to-ask)를 참조하십시오. –

답변

-1

break을 추출하십시오. 그런 다음 break의 제거 얻을 break

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) 
+0

음 ** 누군가 ** 아래 투표권을 누리고 있습니다 ... –

+0

이상하게 들었습니다. 편집 한 후 내 downvote를 철회했습니다 ('dict' 기반 솔루션 추가). 프롬프트의 수가 증가하면 확장 가능한 솔루션을 제공하는 대답은 무엇입니까? 질문과 같이 질문에 대답하는 것은 가치가 있다고 생각하지 않지만 각자 자신에게 맞는 것 같아요. – ShadowRanger

+0

누군가에게 한 것처럼 보입니다. 나도. –

3

와 "종료"할 수있는 옵션 중 하나를, 그래서 루프는 새로운 질문에 대한 프롬프트 유지합니다. 성능을 위해 elif 시험을 후속 if 테스트를 변경 (꼭 필요한 것은, 그러나 당신이이 초기에 공격받을 경우 문자열을 다시 검사 방지) : 물론

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 
관련 문제