Python石头剪刀布开发:computermove未定义及全局变量设置咨询
报错根因
- 完全不需要把
computermove设为全局变量,这个报错和全局作用域没有任何关系,问题出在两个地方:- 你在
computer_rps()函数内部定义的computermove是函数局部变量,只在函数临时运行的作用域里存在,函数执行结束后这个变量就会被回收,外部代码根本无法访问 - 你从头到尾都没调用过
computer_rps()这个函数,也没把它返回的电脑出招结果赋值给主流程的变量,等到了结果判断那行代码,程序在当前作用域找不到名为computermove的变量,自然触发未定义错误
- 你在
- 在这里硬把
computermove设成全局变量纯属负优化,后续如果要加多次对局循环的逻辑,全局的出招值很容易被意外篡改,反而增加调试成本
修复步骤
- 进入对局结果判断的代码块之前,先调用写好的电脑出招函数,把返回值赋值给主流程的
computermove变量,就能正常完成值的传递 - 顺便优化下冗余逻辑:你现在连续三次调用
gameresult()计算同一个对局的结果,属于无意义的重复计算,只要调用一次把返回值存成临时变量,后面判断直接复用就行 - 提个隐藏bug:你现在写的输入校验逻辑完全失效,因为
input()返回的永远是字符串,根本不会抛出ValueError。如果用户输入不在['r','p','s','Q']范围内的字符,gameresult()会因为匹配不到分支返回None,后续转整数的时候会直接报错
关键修复代码片段
# 在gameresult函数定义完成后、结果判断前加入以下代码 computermove = computer_rps() # 调用函数获取电脑出招,赋值给主流程变量 game_result = gameresult(user_move, computermove) # 单次计算对局结果,后续直接复用 if game_result == -1: print("The computer made a choice of ", computermove) print("Looks like the computer won this time...don't let that deter you - let's have another round for a shot at victory!") if game_result == 1: print("The computer made a choice of ", computermove) print('Looks like you won! Excellent choice! But how many times can you make the winning decision...?') if game_result == 0: print("The computer made a choice of ", computermove) print("Looks like it's a tie game - how about another round to settle the score?")
内容的提问来源于stack exchange,提问作者mazuka487
相关产品推荐
相关产品推荐

