Ошибка в программе, в которой указана эта переменная, использованная до объявления - PullRequest
0 голосов
/ 21 июня 2020
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

Здесь я пытаюсь создать простую игру «Камень, ножницы, бумага», в функции check_rock_win в elif l oop это дает ошибку, что переменная 'human' используется до глобального объявления , хотя я заявлял об этом из первых рук.

PS - Я еще новичок в Python!

1 Ответ

1 голос
/ 21 июня 2020

Во всех ваших функциях размещайте операторы global за пределами операторов if, в противном случае он не всегда выполняется, например,

def check_tie():
    global human
    global PC
    # Checks if it's a tie
    if computer == choice:
        print('computer = ', PC, 'you = ', human)
    return
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...