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

如何优化循环与条件语句?精简石头剪刀布代码冗余if分支

Optimizing Rock-Paper-Scissors: Cutting Redundant Conditionals & Refining Loop Logic

Great question! That tangled web of if/elif statements is tough to read and maintain—let’s rewrite this with a smarter, more scalable approach. Here’s how to clean up your code:

1. Replace Conditional Chains with a Winning Rules Dictionary

Instead of manually checking every possible pair, we can define a dictionary that maps each choice to the one it beats. This collapses all those repetitive conditionals into just a couple of simple checks.

Example of the rules dictionary:

winning_pairs = {
    "rock": "scissor",
    "scissor": "paper",
    "paper": "rock"
}

This tells us directly: rock beats scissor, scissor beats paper, paper beats rock.

2. Ditch the Global Variable for a Cleaner Loop

Using a global winner variable to control the game flow is unnecessary. Instead, use a while True loop and break out of it when the user chooses to stop playing—this keeps the code self-contained and easier to follow.

3. Add Input Validation (Optional but Robust)

To handle typos or invalid entries, we can add checks to ensure players only enter valid choices (rock/paper/scissor) before proceeding.


Full Optimized Code

def play_rock_paper_scissors():
    winning_pairs = {"rock": "scissor", "scissor": "paper", "paper": "rock"}
    valid_choices = winning_pairs.keys()

    while True:
        # Get and validate Player 1's choice
        while True:
            choice1 = input("Player 1: please choose rock/paper/scissor! ").lower()
            if choice1 in valid_choices:
                break
            print("Invalid choice! Please enter rock, paper, or scissor.")
        
        # Get and validate Player 2's choice
        while True:
            choice2 = input("Player 2: please choose rock/paper/scissor! ").lower()
            if choice2 in valid_choices:
                break
            print("Invalid choice! Please enter rock, paper, or scissor.")
        
        # Determine the winner in 3 simple checks
        if choice1 == choice2:
            print("It's a draw!")
        elif winning_pairs[choice1] == choice2:
            print("Player 1 is the winner, Congrats!!")
        else:
            print("Player 2 is the winner, Congrats!!")
        
        # Ask to play again with validation
        while True:
            answer = input("Do you want to start a new game? (yes/no) ").lower()
            if answer in ["yes", "no"]:
                break
            print("Please enter 'yes' or 'no'.")
        
        if answer == "no":
            print("See you next time!")
            break
        print("Let's start another game!")

play_rock_paper_scissors()

Key Improvements:

  • No redundant conditionals: The dictionary lets us determine the winner in 3 checks instead of 6+ elif statements.
  • No global variables: The loop uses while True and break for flow control, making the code more modular.
  • Input validation: Players can’t proceed with typos, making the game more user-friendly.
  • Scalability: If you ever want to add extended rules (like lizard/spock), just update the winning_pairs dictionary—no need to add dozens of new conditionals.

内容的提问来源于stack exchange,提问作者oussama z

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:19:23