函数中的一个参数不被替换为变量

2024-04-26 17:21:57 发布

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

我有一个函数,我试图通过它传递一个全局变量。函数的其余部分可以工作,但是当yards1<;=0时,userscore仍然==0。你知道吗

我的假设是7被添加到whoScore中,但是我认为whoScore是一个参数,比如x,它将被userscore替换。我正在寻找一种方法,使它这样userscore或oppscore可以放进触地得分功能。你知道吗

我尝试过将参数重命名为一个字母,z.不起作用

我已经打印了whoScore,并且看到事实上,7被添加到whoScore而不是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。你知道吗


Tags: 函数textlt参数globaldistancedownprint
2条回答

如果要更改userscore的全局值,请在if语句的whoScore+=1行下添加userscore=whoScore。通过runSuccess()获得的“userscore”在函数中被视为whoScore,这意味着它与userscore不同。你知道吗

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

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)

相关问题 更多 >