首页 > 解决方案 > 引用该变量的程序中的错误在声明之前使用

问题描述

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 新手!

标签: pythonpython-3.x

解决方案


在所有函数中,将语句放在global语句之外if,否则,它并不总是被执行,例如,

def check_tie():
    global human
    global PC
    # Checks if it's a tie
    if computer == choice:
        print('computer = ', PC, 'you = ', human)
    return

推荐阅读