变量未替换函数中的参数之一

时间:2019-07-02 03:42:17

标签: python function

我有一个函数,我正在尝试通过它传递全局变量。该功能的其余部分都有效,但是当yards1 <= 0时,userscore仍==0。

我的假设是将7添加到whoScore中,但是我认为由于whoScore是一个参数(如x),因此它将由userscore代替。我正在寻找一种方法,以便可以将userscore或oppscore放入触地得分函数中。

我尝试将参数重命名为单个字母z。没用

我已经打印了whoScore,并且看到实际上是在whoScore中添加了7,而不是userscore。

userscore = 0
oppscore = 0

def runSuccess(text, x, y, whoScore):

    global yards1

    global distance

    global down

    global userscore

    global oppscore

    yardschange1 = random.randint(x, y)
    print(text, "Gain of ", yardschange1, "yards!")
    yards1 -= yardschange1
    down += 1
    distance -= yardschange1
    if yards1 <= 0:
        print("TOUCHDOWN!")
        whoScore += 7
        print("")
        print(whoScore)
        print(userteam, ":", userscore, oppteam, ":", oppscore)

runSuccess("blah", 1, 5, userscore)

我希望userscore替换函数中的whoScore,因为它们在括号中的相同位置,并且userscore ==7。但是,whoScore是通过函数运行的,whoScore == 7。

2 个答案:

答案 0 :(得分:1)

如果您要更改userscore的全局值,请在if语句的whoScore + = 1行下

add userscore = whoScore。您过去在runSuccess()中使用的“ userscore”被视为函数内部的whoScore,这意味着它与userscore不同。

答案 1 :(得分:0)

您需要初始化变量,然后可以使用它。 像这样:

import numpy as np
userscore = 0
oppscore = 0
yards1=0
distance=0
down=0
def runSuccess(text, x, y, whoScore):

  global yards1

  global distance

  global down

  global userscore

  global oppscore

  yardschange1 = np.random.randint(x, y)
  print(text, "Gain of ", yardschange1, "yards!")
  yards1 -= yardschange1
  down += 1
  distance -= yardschange1
  if yards1 <= 0:
      print("TOUCHDOWN!")
      whoScore += 7
      print("")
      print(whoScore)
      print('userteam', ":", userscore, 'oppteam', ":", oppscore)

    runSuccess("blah", 1, 5, userscore)