全局变量不能在单独的函数中修改

时间:2019-11-04 13:53:45

标签: python

我正在尝试制作一个简单的RPS游戏,看不到我在做什么错。 我定义了pc_choise,player_choice并转为全局变量,但无法在checkWinner()之类的函数中对其进行修改。

如果在调用函数后打印该值,它仍然具有初始值。

代码:

    import random
    import sys

    pc_choices = ['r','p','s']
    pc_choise = ''
    player_choice = ''
    turns = 0

    print("\t\tWelcome to Rock Paper Scissors")


    def getPcChoice():
      return random.randint(1,3) - 1

    def getUserChoice():

    player_choice = input('Please choose: ')
    turns = 1

    if(player_choice.lower() not in pc_choices):
      print('\nPlease use R, P, or S -  *not case sensitive*\n')
      getUserChoice()
    else:
      pc_choise = pc_choices[getPcChoice()]
      print('\nYou picked ' + player_choice + ' and the PC picked ' + 
      pc_choise)
      checkWinner()

    def checkWinner():



      if(player_choice.lower() == pc_choise.lower()):
        print('Tie')
      elif(player_choice.lower() == 'r' and pc_choise.lower() == 'p'
        or   player_choice.lower() == 'p' and pc_choise.lower() == 's'
        or   player_choice.lower() == 's' and pc_choise.lower() == 'r'):
        print('You win! ?')
      else:
        print('You lose! ?')


    getUserChoice()

2 个答案:

答案 0 :(得分:2)

在代码的第一行中添加以下代码:

global pc_choicesglobal pc_choice

这是为了标记将使用的变量是全局变量。

答案 1 :(得分:0)

您需要在函数范围内将变量声明为global,以便Python解释器可以相应地解释它们,否则,默认情况下它们将获得函数范围。我还发现了已解决的缩进问题。下面是修改后的代码:

import random
import sys

pc_choices = ['r','p','s']

pc_choise = ''
player_choice = ''
turns = 0

print("\t\tWelcome to Rock Paper Scissors")

def getPcChoice():
    return random.randint(1,3) - 1

def getUserChoice():
    global pc_choise
    global player_choice

    player_choice = input('Please choose: ')
    turns = 1

    if(player_choice.lower() not in pc_choices):
        print('\nPlease use R, P, or S -  *not case sensitive*\n')
        getUserChoice()
    else:
        pc_choise = pc_choices[getPcChoice()]
        print('\nYou picked ' + player_choice + ' and the PC picked ' + pc_choise)
        checkWinner()

def checkWinner():
    global pc_choise
    global player_choice

    if(player_choice.lower() == pc_choise.lower()):
        print('Tie')
    elif(player_choice.lower() == 'r' and pc_choise.lower() == 'p'
        or   player_choice.lower() == 'p' and pc_choise.lower() == 's'
        or   player_choice.lower() == 's' and pc_choise.lower() == 'r'):
        print('You win! ?')
    else:
        print('You lose! ?')

getUserChoice()

但是,正如@mario_sunny在评论中所建议的那样,最好避免使用全局变量。