You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python圣经经文查询代码中的冗余if-else重构为函数?

Refactoring Your Bible Verse Lookup Code (Ditching the Messy If-Else Blocks)

Absolutely! Those endless if-else chains get unwieldy fast—refactoring them into a cleaner structure (using dictionaries and functions) will make your code way easier to maintain, read, and extend, while keeping every bit of your original functionality and interaction flow intact. Let’s walk through how to do it.

First, Let’s Assume Your Original Code Looks Something Like This

I’m guessing you’ve got a function that looks a lot like this, with a long list of conditionals for each emotion:

def get_bible_verse(emotion):
    if emotion == "Angry":
        return "Ephesians 4:26: 'In your anger do not sin': Do not let the sun go down while you are still angry."
    elif emotion == "Confused":
        return "Proverbs 3:5-6: Trust in the Lord with all your heart and lean not on your own understanding; in all your ways submit to him, and he will make your paths straight."
    elif emotion == "Sad":
        return "Psalm 34:18: The Lord is close to the brokenhearted and saves those who are crushed in spirit."
    elif emotion == "Anxious":
        return "Philippians 4:6-7: Do not be anxious about anything, but in every situation, by prayer and petition, with thanksgiving, present your requests to God."
    # ... dozens more elif branches piling up
    else:
        return "Psalm 23:1: The Lord is my shepherd, I lack nothing."

The problem here is obvious: every time you add a new emotion, you have to write a new elif line, and the function gets longer and harder to scan. Let’s fix that.

Option 1: Use a Dictionary for Simple Emotion-to-Verse Mapping

If your logic is just "return a specific verse for each emotion," a dictionary is perfect. It’s clean, fast, and easy to update:

# First, define a dictionary that maps each emotion to its verse
EMOTION_VERSES = {
    "Angry": "Ephesians 4:26: 'In your anger do not sin': Do not let the sun go down while you are still angry.",
    "Confused": "Proverbs 3:5-6: Trust in the Lord with all your heart and lean not on your own understanding; in all your ways submit to him, and he will make your paths straight.",
    "Sad": "Psalm 34:18: The Lord is close to the brokenhearted and saves those who are crushed in spirit.",
    "Anxious": "Philippians 4:6-7: Do not be anxious about anything, but in every situation, by prayer and petition, with thanksgiving, present your requests to God."
    # Add new emotion-verse pairs here—no need to touch the function!
}

# Define your default verse for unrecognized emotions
DEFAULT_VERSE = "Psalm 23:1: The Lord is my shepherd, I lack nothing."

def get_bible_verse(emotion):
    # Use the dictionary's `get()` method to fetch the verse (or default if not found)
    # We also add strip() and capitalize() to handle user input inconsistencies
    cleaned_emotion = emotion.strip().capitalize()
    return EMOTION_VERSES.get(cleaned_emotion, DEFAULT_VERSE)

Why This Works:

  • No more conditionals: Adding a new emotion only requires a new line in the EMOTION_VERSES dictionary.
  • Cleaner readability: Anyone glancing at the code can immediately see which emotions map to which verses.
  • Robust input handling: The strip().capitalize() ensures things like " angry " or "angry" still match the "Angry" key.

Option 2: Use Function Handlers for Complex Logic

If some emotions need extra steps (like printing a custom message, logging the request, or modifying the verse based on other inputs), map emotions to small, focused functions instead:

# Define a handler function for each emotion
def handle_angry():
    verse = "Ephesians 4:26: 'In your anger do not sin': Do not let the sun go down while you are still angry."
    print("Remember: anger is natural, but don’t let it lead you to sin.")
    return verse

def handle_confused():
    verse = "Proverbs 3:5-6: Trust in the Lord with all your heart and lean not on your own understanding; in all your ways submit to him, and he will make your paths straight."
    print("God’s wisdom is greater than our own—seek Him for guidance.")
    return verse

def handle_sad():
    verse = "Psalm 34:18: The Lord is close to the brokenhearted and saves those who are crushed in spirit."
    print("You are not alone in your sadness; God is with you.")
    return verse

def handle_default():
    verse = "Psalm 23:1: The Lord is my shepherd, I lack nothing."
    print("Here’s a comforting verse for you:")
    return verse

# Map emotions to their handler functions
EMOTION_HANDLERS = {
    "Angry": handle_angry,
    "Confused": handle_confused,
    "Sad": handle_sad
    # Add new emotion-handler pairs here
}

def get_bible_verse(emotion):
    cleaned_emotion = emotion.strip().capitalize()
    # Get the handler function (or default if emotion isn't recognized)
    handler = EMOTION_HANDLERS.get(cleaned_emotion, handle_default)
    # Call the handler and return the verse
    return handler()

Why This Works:

  • Separation of concerns: Each handler takes care of exactly one emotion’s logic, making it easy to test or modify individual cases without breaking the rest.
  • Scalability: If you need to add extra logic (like sending a follow-up question) for a specific emotion, you just update its handler function—not the main get_bible_verse logic.

Keep Your Interaction Flow Intact

The best part? Your existing user interaction code doesn’t need any changes. For example, if you had something like this:

def main():
    print("How are you feeling today? (Angry, Confused, Sad, Anxious, etc.)")
    user_emotion = input("> ")
    verse = get_bible_verse(user_emotion)
    print(f"\nHere's a verse for you:\n{verse}")

if __name__ == "__main__":
    main()

It will work exactly the same with either refactored version of get_bible_verse. The function’s input (an emotion string) and output (a verse string) stay consistent, so your users won’t notice any difference in the experience.

Key Benefits of This Refactor

  • Maintainability: No more hunting through a wall of if-elif-else to add or change verses.
  • Readability: The code’s purpose is immediately clear—anyone can see how emotions connect to verses or logic.
  • Flexibility: It’s easy to expand later (add new emotions, add more complex logic) without messy rewrites.

内容的提问来源于stack exchange,提问作者Chris Nathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:33:37