Python聊天响应程序逻辑问题求助:条件判断引发误退出
解决随机提问后答案匹配冲突导致程序异常退出的问题
Got it, let's break down what's tripping up your code right now:
Your core issue is that you're checking the user's response against all three possible answers, regardless of which question was actually asked. For example, if the randomizer picks the "How are you feeling?" question and the user replies "tired", the first if passes—but then the code immediately checks if the response is "yes" (for the homesick question), which it isn't, so it triggers exit() before ever getting to the logic that matters for the question that was asked.
Here's a cleaned-up, fixed version of your code:
import random def main(): user_name = input("What is your name? ") # Bundle each question with its correct answer and corresponding responses question_setups = [ { "question": f"How are you feeling right now {user_name}?", "expected_answer": "tired", "replies": [ 'I wish I can make you feel better.', 'I hope school is not making you feel stressed.', 'You deserve the right to relax.' ] }, { "question": "Do you miss your home?", "expected_answer": "yes", "replies": [ "Don't worry, you will be home soon......", 'I am protecting your family and loved ones, trust me on this.', "Your kingdoms has been waiting for a long time, they'd forgiven your mistakes" ] }, { "question": "Who do you miss?", "expected_answer": "my mom", "replies": ["Mom will be in town soon"] } ] # Pick a random question configuration chosen_question = random.choice(question_setups) user_response = input(chosen_question["question"]) # Only check against the answer for the question we actually asked if user_response == chosen_question["expected_answer"]: print(random.choice(chosen_question["replies"])) else: # Exit only if the answer doesn't match the selected question's expected answer exit() if __name__ == "__main__": main()
Key improvements in this code:
- Grouped question logic: Each question, its correct answer, and its possible replies are bundled together in a dictionary. This way, when we pick a random question, we have all the related info we need in one place—no more cross-checking against unrelated answers.
- Single conditional check: We only compare the user's response to the expected answer of the question that was actually asked. No more cascading
if/elseblocks that trigger exits for the wrong reasons. - Cleaner structure: Removed unnecessary nested functions to make the code easier to read and modify later.
Bonus tweaks you might want to add:
- If you want to accept multiple valid answers (like "yes" or "y" for the homesick question), change
expected_answerto a list (e.g.,["yes", "y"]) and update the check toif user_response.lower() in chosen_question["expected_answer"]. - Make the exit more user-friendly by adding a message before exiting:
print("Oops, that's not the answer I was looking for."); exit()
内容的提问来源于stack exchange,提问作者user9196658




