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

while循环中loss()、win()、draw()函数未正确调用致分数不更新

Hey there! Let's figure out why your score-tracking functions aren't working correctly in the loop. The main issues here are variable scope confusion and a tiny typo—let's break this down step by step.

1. The Core Problem: Variable Scope

Right now, when you try to update scoreH and scoreAI inside loss(), win(), and draw(), you're actually creating local variables with the same name instead of modifying the global score variables you defined at the top. Python treats variables inside functions as local by default unless you explicitly tell it to use the global version. So your functions were updating temporary local values that vanished after the function finished, leaving your global scores untouched.

2. A Tiny Typo in draw()

You also have a typo in the draw() function: you wrote scoreAi (lowercase 'i') instead of scoreAI (uppercase 'I'). That would throw an error if a draw ever occurred, breaking the game flow.

Fixed Code with Explanations

Here's the corrected version, with improvements for readability and functionality:

from random import randint
print("Welcome to this game of rock paper scissors against the computer.")
print("Good luck and have fun! Enjoy this game! ")
print("To stop playing, type quit when the round ends. If you want to continue playing, press any key ")
scoreH = 0
scoreAI = 0
Round = 0

def loss():
    # Declare we're modifying the global score variables, not creating local ones
    global scoreH, scoreAI
    scoreAI += 1  # Shorthand for scoreAI = scoreAI + 1

def win():
    global scoreH, scoreAI
    scoreH += 1

def draw():
    global scoreH, scoreAI
    # Fixed the typo here (scoreAI instead of scoreAi)
    pass  # No score changes needed, so "pass" keeps the function valid

x = True
while x == True :
    Round += 1
    print(f"Round {Round} is going to start. ")
    print("1.Rock")
    print("2.Paper")
    print("3.Scissors")
    choice = input("Enter your choice: ").lower()
    IntChoice = randint(1,3)
    
    # Convert AI's integer choice to string
    if IntChoice == 1:
        AI_choice = "rock"
    elif IntChoice == 2:
        AI_choice = "paper"
    elif IntChoice == 3:
        AI_choice = "scissors"
    print(AI_choice)
    
    # Check game results
    if choice == AI_choice:
        draw()
        print(f"The computer chose {AI_choice}. You draw.")
    elif (choice == "paper" and AI_choice == "rock") or \
         (choice == "scissors" and AI_choice == "paper") or \
         (choice == "rock" and AI_choice == "scissors"):
        win()
        print(f"The computer chose {AI_choice}. You win.")
    elif (AI_choice == "paper" and choice == "rock") or \
         (AI_choice == "scissors" and choice == "paper") or \
         (AI_choice == "rock" and choice == "scissors"):
        loss()
        print(f"The computer chose {AI_choice}. You lose.")
    else:
        print("Invalid input.")
        continue
    
    end = input()
    # Make quit/stop case-insensitive
    if end.lower() in ["stop", "quit"]:
        print(f"The score is : {scoreH} - {scoreAI}")
        if scoreH > scoreAI:
            print("You win the overall game!")
        elif scoreH < scoreAI:
            print("You lose the overall game.")
        else:
            print("The overall game is a draw.")
        break
    else:
        continue

Key Improvements:

  • Added global scoreH, scoreAI to each function to ensure we're modifying the global score variables.
  • Fixed the scoreAi typo in draw() and simplified it with pass since no score changes are needed.
  • Used f-strings for cleaner, more readable print statements.
  • Grouped winning/losing conditions into single elif blocks to reduce code repetition.
  • Made the quit/stop check case-insensitive so inputs like "Quit" or "STOP" work.

Alternative: Avoid Global Variables (Better Practice)

If you want to avoid global variables (which makes code more modular and easier to debug), you can pass scores as arguments and return updated values:

def loss(scoreH, scoreAI):
    return scoreH, scoreAI + 1

def win(scoreH, scoreAI):
    return scoreH + 1, scoreAI

def draw(scoreH, scoreAI):
    return scoreH, scoreAI

# Call the functions like this:
scoreH, scoreAI = draw(scoreH, scoreAI)
scoreH, scoreAI = win(scoreH, scoreAI)

This approach keeps your function logic independent of global state, which is great for larger projects.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 14:57:38