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

Python函数内操作变量时comp_sc无法累计累加问题咨询

问题原因
  • 运算符书写错误:代码中使用了comp_sc =+ turn_score,该语法等价于comp_sc = +turn_score,作用是将当前turn_score的正值直接赋值给comp_sc,而非累加,这是导致comp_sc始终等于当前turn_score的核心原因,正确的累加运算符为+=。
  • 变量作用域与返回值处理错误:
    • 全局定义的comp_sc是整数类型(Python中的不可变类型),作为参数传入com_move函数时,函数内操作的是局部同名参数,不会直接修改全局变量的值
    • main函数的循环中调用com_move时,没有接收函数返回的累加结果,每次循环仍然传入初始值0,导致无法多轮累加
  • 全局变量修改未声明:在com_move和main函数中修改全局变量game_start时,没有添加global声明,会被Python判定为局部变量,运行时会触发未定义报错。
解决方法
  1. 将所有=+替换为正确的累加运算符+=
  2. 在main函数的循环中接收com_move的返回值,更新全局comp_sc,也可以直接声明comp_sc为全局变量后在函数内直接操作
  3. 在所有修改全局变量game_start、comp_sc的函数内添加global声明,避免作用域冲突
修正后参考代码
import random
comp_sc = 0
game_start = False

def main():
    global game_start, comp_sc
    turn_start = input('Are you Ready to play? ').lower()
    if turn_start == 'n':
        game_start = False
        print('No one is willing to play!!!')
    if turn_start == 'y':
        game_start = True
        comp_sc = 0 # 开局重置分数

    # while game_start == True:
    for x in range(1, 5):
        if not game_start:
            break
        comp_sc = com_move(comp_sc)
    print(f"最终电脑得分:{comp_sc}")

def roll():
    # 生成1-6的随机整数
    return random.randint(1,6)

def com_move(comp_sc):
    global game_start
    turn_score = int(roll())
    if turn_score < 6:
        comp_sc += turn_score
        print(comp_sc, 'comp_sc')
    elif turn_score == 6:
        # 掷到6不得分,结束游戏
        comp_sc += 0
        game_start = False
    return comp_sc

if __name__ == "__main__":
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:18:02