python - 引用该变量的程序中的错误在声明之前使用
问题描述
import random
rps = ['Rock', 'Paper', 'Scissor']
diction = {'R': 'Rock', 'P': 'Paper', 'S': 'Scissor'}
human = 0
PC = 0
print('R : Rock \n P : Paper \n S : Scissor')
computer = random.choice(rps)
player = input().capitalize()
choice = diction[player]
print(computer, ' vs. ', choice)
# Check for a tie
def check_tie():
# Checks if it's a tie
if computer == choice:
global human
global PC
print('computer = ', PC, 'you = ', human)
return
# Check for a win
def check_win():
check_rock_win()
check_paper_win()
check_scissor_win()
return
# Check if rock wins
def check_rock_win():
if computer == 'Rock' and choice == 'Scissor':
global human
global PC
human = human + 0
PC = PC + 1
print('computer = ', PC, 'you = ', human)
elif computer == 'Scissor' and choice == 'Rock':
global human
global PC
human = human + 1
PC = PC + 0
print('computer = ', PC, 'you = ', human)
return
# check if paper wins
def check_paper_win():
if computer == 'Rock' and choice == 'Paper':
global human
global PC
human = human + 1
PC = PC + 0
print('computer = ', PC, 'you = ', human)
elif computer == 'Paper' and choice == 'Rock':
global human
global PC
human = human + 0
PC = PC + 1
print('computer = ', PC, 'you = ', human)
return
# check if scissor wins
def check_scissor_win():
if computer == 'Scissor' and choice == 'Paper':
global human
global PC
human = human + 0
PC = PC + 1
print('computer = ', PC, 'you = ', human)
elif computer == 'Paper' and choice == 'Scissor':
global human
global PC
human = human + 1
PC = PC + 0
print('computer = ', PC, 'you = ', human)
return
在这里,我正在尝试制作一个简单的 Rock,Paper,scissor 游戏,在 elif 循环的函数 check_rock_win 中,它给出了一个错误,即在全局声明之前使用了变量 'human',尽管我已经直接声明了它。
PS - 我还是 Python 新手!
解决方案
在所有函数中,将语句放在global
语句之外if
,否则,它并不总是被执行,例如,
def check_tie():
global human
global PC
# Checks if it's a tie
if computer == choice:
print('computer = ', PC, 'you = ', human)
return
推荐阅读
- javascript - 为什么 Object.prototype.hasOwnProperty 不等于 instance.__proto__.hasOwnProperty
- line-breaks - 使用 Mathjax HTML 换行
- python - 罗马尼亚地图问题中的统一成本搜索
- reactjs - 尽管我已删除该项目,但旧项目仍会在端口 3000 上加载
- mysql - 使用bash将变量中的多行字符串添加到mysql中
- java - intellij插件开发中的proguard问题
- ios - 无法快速解析 json 数据
- python - numpy 数组输入到 tensorflow/keras 神经网络的 dtype 是否重要?
- laravel-7 - Laravel 中的损坏图像
- firebase - 为什么此快照将每个文档获取两次?扑