计数器变量“未赋值?”

2024-09-30 04:37:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python做一个简单的石头、布、剪刀的游戏,而计数器变量作为一个错误出现,我和我的计算机科学似乎都无法定位。你知道吗

import random
options = ["R", "P", "S"]
userwin = 0
computerwin = 0
counter = 0

def RPS():
    counter = counter + 1
    computerchoice = random.choice(options)
    print ("It's round number", counter, "!")
    humanchoice = input ("Do you choose rock [R], paper [P] or scissors[S]?")

    if computerchoice == "R":
        if humanchoice == "R":
            print ("Rock grinds rock - it's a draw!")
        if humanchoice == "P":
            print ("Paper wraps rock - you win!")
            userwin = userwin + 1
        if humanchoice == "S":
            print ("Rock blunts scissors - you lost!")
            computerwin = computerwin + 1

    if computerchoice == "S":
        if humanchoice == "S":
            print ("Scissors strikes scissors - it's a draw!")
        if humanchoice == "R":
            print ("Rock blunts scissors - you win!")
            userwin = userwin + 1
            if humanchoice == "P":
                print ("Scissors cuts paper - you lost!")
                computerwin = computerwin + 1

    if computerchoice == "P":
        if humanchoice == "P":
            print ("Paper folds paper - it's a draw!")
        if humanchoice == "S":
            print ("Scissors cuts paper - you win!")
            userwin = userwin + 1
        if humanchoice == "S":
            print ("Paper wraps scissors - you lost!")
            computerwin = computerwin + 1

while userwin < 10 or computerwin < 10:
    RPS()

出现的错误是

counter = counter + 1
UnboundLocalError: local variable 'counter' referenced before assignment

我以前没有遇到过这个错误-我不确定如何修复它。有什么想法吗?谢谢您!你知道吗


Tags: youif错误counteritpaperprintdraw
1条回答
网友
1楼 · 发布于 2024-09-30 04:37:57

您不能在函数中分配全局变量,您需要像这样做:

def RPS():
    global counter

    counter = counter + 1
    computerchoice = random.choice(options)

必须对函数外定义的每个变量执行此操作。你知道吗

相关问题 更多 >

    热门问题