"变量___在分配之前被引用。"

时间:2015-03-31 00:28:59

标签: python variables

我的Python程序遇到了一些困难。它播放Rock Paper Scissors。代码非常大,因此我将其缩短为示例程序,但可以在https://github.com/Ph0enix0/doitall/blob/master/computerpungramming/rockpaperscissors.py查看完整代码

(数量是比赛的数量)

count = 0
user_wins = 0
comp_wins = 0

def game():

    comp_answer = ['rock', 'paper', 'scissors']
    user_answer = input('Rock, paper, or scissors?')

    if user_answer = 'rock':
        count += 1

        if comp_answer = 'paper':
            print('Paper! I win!)
            comp_wins += 1
#The rest of the comparisons are here
while 1 == 1:
game()

如果我把变量放在游戏中(),他们每次都会重置。帮助

3 个答案:

答案 0 :(得分:2)

您需要在函数内移动变量并定义scissors_wins

def game():
    '''
    The actual game code. The code randomly chooses
    rock, paper, or scissors. Then, it checks if the user's choice
    beats the computer's. If it does, the user wins, and vice versa.
    '''

    #User picks rock, paper, or scissors.
    user_answer = input('Rock, paper, or scissors? ')


    #Tell the code that the game is not finished. Used for while loops.
    game_finished = False
    count = 0
    user_wins = 0
    comp_wins = 0
    scissors_wins = 0

你的游戏已有循环,所以除非你在while 1 == 1中做某事,否则只需致电game()

是的,每次调用函数时,变量都将重置为0。

如果你想让win计数在多次运行中持续存在,请使用dict在函数外声明:

d = {"user":0,"comp":0,"scissor":0}

然后在每场比赛结束时更新:

 d["user"] += user_wins 

或者增加函数内部的计数而不是使用变量。

您似乎也没有打破循环,因此您的代码将无限循环。我想你也想多次询问用户输入,所以在循环中移动user_answer = input('Rock, paper, or scissors? ')

如下所示:

d = {"user":0,"comp":0,"scissor":0}

d = {" user":0," comp":0," scissor":0}

def game():
    '''
    The actual game code. The code randomly chooses
    rock, paper, or scissors. Then, it checks if the user's choice
    beats the computer's. If it does, the user wins, and vice versa.
    '''  

    #Tell the code that the game is not finished. Used for while loops.
    game_finished = False
    count = 0
    user_wins = 0
    comp_wins = 0
    scissors_wins = 0

    #Game isn't finished, so the code continues.
    while not game_finished:
            user_answer = input('Rock, paper, or scissors? ')

   # update dict with totals when loop breaks

答案 1 :(得分:1)

game功能无法更改其外的变量(countuser_winscomp_wins)。让函数返回必要的值。

count = 0
user_wins = 0
comp_wins = 0
def game():
    ...
    return count, user_wins, comp_wins
count, user_wins, comp_wins = game()

答案 2 :(得分:0)

你想要改变

if comp_answer = 'paper':

if comp_answer == 'paper':

这可能是错误的原因。在您要检查if条件的任何其他地方更改= to ==。