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

Python实现正确的分数更新系统(解决函数调用后分数重置问题)

问题原因

核心问题出在变量作用域与返回值未接收:

  • win()和lose()函数里的humanscore、computerscore是局部参数,修改后虽然返回了新值,但你没有把这个新值重新赋值给全局的分数变量,导致全局分数始终停留在初始的0。
  • 最后输入错误的判断逻辑有误,if human != R:会导致选择P或S时也弹出错误提示。
修复后的代码
import random
R = "ROCK"
P = "PAPER"
S = "SCİSSORS"
print("Welcome to 'Rock Paper Scissors' game!\n")

humanscore = 0
computerscore = 0

# 改为参数传递变量,避免依赖全局变量
def end(computer, human):
    print("\n\n\n\n\n")
    print("Computer's weapon =", computer)
    print("Your weapon =", human, "\n\n\n")

def win(humanscore):
    print("You win!")
    humanscore += 1
    return humanscore

def lose(computerscore):
    print("You lose!")
    computerscore += 1
    return computerscore

def Score(humanscore, computerscore):
    score = f"Human Score = {humanscore}, Computer Score = {computerscore}"
    print(score)


while True:
    allweapon = (R, P, S)
    computer = random.choice(allweapon)
    print(f"1. {R}\n2. {P}\n3. {S}\n")
    human = str.upper(input("Choose your weapon!\n"))

    if human == R:
        if computer == S:
            end(computer, human)
            # 接收返回的新分数,更新全局变量
            humanscore = win(humanscore)
            Score(humanscore, computerscore)
        elif computer == P:
            end(computer, human)
            computerscore = lose(computerscore)
            Score(humanscore, computerscore)
    elif human == S:
        if computer == P:
            end(computer, human)
            humanscore = win(humanscore)
            Score(humanscore, computerscore)
        elif computer == R:
            end(computer, human)
            computerscore = lose(computerscore)
            Score(humanscore, computerscore)
    elif human == P:
        if computer == S:
            end(computer, human)
            computerscore = lose(computerscore)
            Score(humanscore, computerscore)
        elif computer == R:
            end(computer, human)
            humanscore = win(humanscore)
            Score(humanscore, computerscore)
    elif human == computer:
        end(computer, human)
        Score(humanscore, computerscore)
        print("Tied!")
    # 仅在输入无效时提示错误
    else:
        print("There is no such weapon!\n")
关键修改说明
  1. 接收函数返回值:调用win()和lose()时,将返回的新分数重新赋值给全局变量(比如humanscore = win(humanscore)),确保全局分数能持续更新。
  2. 修正输入判断逻辑:用elif和else替代独立if,避免有效输入触发错误提示。
  3. 优化函数耦合:修改end()函数为参数传递模式,减少对全局变量的依赖,代码更规范。

内容的提问来源于stack exchange,提问作者Ahmet KAYABAŞ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:20:35